window-basic-main.cpp 210.4 KB
Newer Older
1
/******************************************************************************
2
    Copyright (C) 2013-2015 by Hugh Bailey <obs.jim@gmail.com>
J
jp9000 已提交
3
                               Zachary Lund <admin@computerquip.com>
4
                               Philippe Groarke <philippe.groarke@gmail.com>
5 6 7

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
8
    the Free Software Foundation, either version 2 of the License, or
9 10 11
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
12
    but WITHOUT ANY WARRANTY; without even the implied warranty of
13 14 15 16 17 18 19
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/

S
Shaolin 已提交
20
#include <ctime>
J
jp9000 已提交
21
#include <obs.hpp>
22
#include <QGuiApplication>
J
jp9000 已提交
23
#include <QMessageBox>
24
#include <QShowEvent>
25
#include <QDesktopServices>
J
jp9000 已提交
26
#include <QFileDialog>
27
#include <QDesktopWidget>
28
#include <QScreen>
29 30
#include <QColorDialog>
#include <QSizePolicy>
V
VodBox 已提交
31
#include <QScrollBar>
32
#include <QTextStream>
33

J
jp9000 已提交
34
#include <util/dstr.h>
35 36
#include <util/util.hpp>
#include <util/platform.h>
P
Palana 已提交
37
#include <util/profiler.hpp>
38
#include <util/dstr.hpp>
39

40
#include "obs-app.hpp"
41
#include "platform.hpp"
42
#include "visibility-item-widget.hpp"
43
#include "item-widget-helpers.hpp"
44
#include "window-basic-settings.hpp"
45
#include "window-namedialog.hpp"
J
jp9000 已提交
46
#include "window-basic-auto-config.hpp"
J
jp9000 已提交
47
#include "window-basic-source-select.hpp"
J
jp9000 已提交
48
#include "window-basic-main.hpp"
J
jp9000 已提交
49
#include "window-basic-stats.hpp"
J
jp9000 已提交
50
#include "window-basic-main-outputs.hpp"
J
jp9000 已提交
51
#include "window-log-reply.hpp"
J
jp9000 已提交
52
#include "window-projector.hpp"
P
Palana 已提交
53
#include "window-remux.hpp"
J
jp9000 已提交
54
#include "qt-wrappers.hpp"
55
#include "display-helpers.hpp"
56
#include "volume-control.hpp"
57
#include "remote-text.hpp"
J
JohannMG 已提交
58
#include "ui-validation.hpp"
S
Shaolin 已提交
59 60
#include <fstream>
#include <sstream>
61

62
#ifdef _WIN32
J
jp9000 已提交
63
#include "win-update/win-update.hpp"
64
#include "windows.h"
J
jp9000 已提交
65 66
#endif

J
jp9000 已提交
67
#include "ui_OBSBasic.h"
68
#include "ui_ColorSelect.h"
69

J
jp9000 已提交
70
#include <fstream>
71 72
#include <sstream>

73 74 75
#include <QScreen>
#include <QWindow>

J
jp9000 已提交
76 77 78
#include <json11.hpp>

using namespace json11;
79
using namespace std;
J
jp9000 已提交
80

81
#ifdef BROWSER_AVAILABLE
82
#include <browser-panel.hpp>
J
jp9000 已提交
83 84
#endif

J
jp9000 已提交
85 86
#include "ui-config.h"

J
jp9000 已提交
87
struct QCef;
88 89
struct QCefCookieManager;

J
jp9000 已提交
90
QCef *cef = nullptr;
91 92 93
QCefCookieManager *panel_cookies = nullptr;

void DestroyPanelCookieManager();
J
jp9000 已提交
94

J
jp9000 已提交
95 96
namespace {

J
jp9000 已提交
97
template<typename OBSRef> struct SignalContainer {
J
jp9000 已提交
98 99 100 101 102
	OBSRef ref;
	vector<shared_ptr<OBSSignal>> handlers;
};
}

103 104
extern volatile long insideEventLoop;

J
jp9000 已提交
105 106
Q_DECLARE_METATYPE(OBSScene);
Q_DECLARE_METATYPE(OBSSceneItem);
P
Palana 已提交
107
Q_DECLARE_METATYPE(OBSSource);
J
jp9000 已提交
108
Q_DECLARE_METATYPE(obs_order_movement);
J
jp9000 已提交
109
Q_DECLARE_METATYPE(SignalContainer<OBSScene>);
J
jp9000 已提交
110

V
VodBox 已提交
111 112 113 114 115 116 117 118 119 120 121 122
QDataStream &operator<<(QDataStream &out, const SignalContainer<OBSScene> &v)
{
	out << v.ref;
	return out;
}

QDataStream &operator>>(QDataStream &in, SignalContainer<OBSScene> &v)
{
	in >> v.ref;
	return in;
}

J
jp9000 已提交
123
template<typename T> static T GetOBSRef(QListWidgetItem *item)
P
Palana 已提交
124 125 126 127
{
	return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>();
}

J
jp9000 已提交
128
template<typename T> static void SetOBSRef(QListWidgetItem *item, T &&val)
P
Palana 已提交
129 130
{
	item->setData(static_cast<int>(QtDataRole::OBSRef),
J
jp9000 已提交
131
		      QVariant::fromValue(val));
P
Palana 已提交
132 133
}

134 135
static void AddExtraModulePaths()
{
136
	char base_module_dir[512];
137 138
#if defined(_WIN32) || defined(__APPLE__)
	int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir),
J
jp9000 已提交
139
				     "obs-studio/plugins/%module%");
140
#else
141
	int ret = GetConfigPath(base_module_dir, sizeof(base_module_dir),
J
jp9000 已提交
142
				"obs-studio/plugins/%module%");
143
#endif
B
BtbN 已提交
144

145
	if (ret <= 0)
146 147
		return;

J
jpark37 已提交
148
	string path = base_module_dir;
149
#if defined(__APPLE__)
150
	obs_add_module_path((path + "/bin").c_str(), (path + "/data").c_str());
151

J
jp9000 已提交
152 153 154 155
	BPtr<char> config_bin =
		os_get_config_path_ptr("obs-studio/plugins/%module%/bin");
	BPtr<char> config_data =
		os_get_config_path_ptr("obs-studio/plugins/%module%/data");
156 157
	obs_add_module_path(config_bin, config_data);

158 159
#elif ARCH_BITS == 64
	obs_add_module_path((path + "/bin/64bit").c_str(),
J
jp9000 已提交
160
			    (path + "/data").c_str());
161 162
#else
	obs_add_module_path((path + "/bin/32bit").c_str(),
J
jp9000 已提交
163
			    (path + "/data").c_str());
164
#endif
165 166
}

167 168
extern obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main);

169 170
void assignDockToggle(QDockWidget *dock, QAction *action)
{
J
jp9000 已提交
171
	auto handleWindowToggle = [action](bool vis) {
172 173 174 175
		action->blockSignals(true);
		action->setChecked(vis);
		action->blockSignals(false);
	};
J
jp9000 已提交
176
	auto handleMenuToggle = [dock](bool check) {
177 178 179 180 181 182
		dock->blockSignals(true);
		dock->setVisible(check);
		dock->blockSignals(false);
	};

	dock->connect(dock->toggleViewAction(), &QAction::toggled,
J
jp9000 已提交
183 184
		      handleWindowToggle);
	dock->connect(action, &QAction::toggled, handleMenuToggle);
185 186
}

J
jp9000 已提交
187
extern void RegisterTwitchAuth();
J
jp9000 已提交
188
extern void RegisterMixerAuth();
S
SoftArch 已提交
189
extern void RegisterRestreamAuth();
J
jp9000 已提交
190

191
OBSBasic::OBSBasic(QWidget *parent)
J
jp9000 已提交
192
	: OBSMainWindow(parent), ui(new Ui::OBSBasic)
193
{
V
VodBox 已提交
194 195 196
	qRegisterMetaTypeStreamOperators<SignalContainer<OBSScene>>(
		"SignalContainer<OBSScene>");

197 198
	setAttribute(Qt::WA_NativeWindow);

J
jp9000 已提交
199 200 201
#if TWITCH_ENABLED
	RegisterTwitchAuth();
#endif
J
jp9000 已提交
202 203 204
#if MIXER_ENABLED
	RegisterMixerAuth();
#endif
S
SoftArch 已提交
205 206 207
#if RESTREAM_ENABLED
	RegisterRestreamAuth();
#endif
J
jp9000 已提交
208

J
jp9000 已提交
209 210
	setAcceptDrops(true);

211 212 213 214
	setContextMenuPolicy(Qt::CustomContextMenu);
	connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this,
		SLOT(on_customContextMenuRequested(const QPoint &)));

215 216
	api = InitializeAPIInterface(this);

217
	ui->setupUi(this);
218
	ui->previewDisabledWidget->setVisible(false);
J
jp9000 已提交
219

J
jp9000 已提交
220 221
	startingDockLayout = saveState();

222
	statsDock = new OBSDock();
223 224 225 226 227 228 229 230
	statsDock->setObjectName(QStringLiteral("statsDock"));
	statsDock->setFeatures(QDockWidget::AllDockWidgetFeatures);
	statsDock->setWindowTitle(QTStr("Basic.Stats"));
	addDockWidget(Qt::BottomDockWidgetArea, statsDock);
	statsDock->setVisible(false);
	statsDock->setFloating(true);
	statsDock->resize(700, 200);

S
Socapex 已提交
231
	copyActionsDynamicProperties();
232

233
	char styleSheetPath[512];
J
jp9000 已提交
234
	int ret = GetProfilePath(styleSheetPath, sizeof(styleSheetPath),
J
jp9000 已提交
235
				 "stylesheet.qss");
236
	if (ret > 0) {
H
HomeWorld 已提交
237
		if (QFile::exists(styleSheetPath)) {
J
jp9000 已提交
238 239
			QString path =
				QString("file:///") + QT_UTF8(styleSheetPath);
H
HomeWorld 已提交
240 241
			App()->setStyleSheet(path);
		}
242 243
	}

J
jp9000 已提交
244
	qRegisterMetaType<OBSScene>("OBSScene");
P
Palana 已提交
245
	qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
J
jp9000 已提交
246
	qRegisterMetaType<OBSSource>("OBSSource");
P
Palana 已提交
247
	qRegisterMetaType<obs_hotkey_id>("obs_hotkey_id");
248
	qRegisterMetaType<SavedProjectorInfo *>("SavedProjectorInfo *");
P
Palana 已提交
249

J
jp9000 已提交
250 251
	qRegisterMetaTypeStreamOperators<std::vector<std::shared_ptr<OBSSignal>>>(
		"std::vector<std::shared_ptr<OBSSignal>>");
252
	qRegisterMetaTypeStreamOperators<OBSScene>("OBSScene");
253
	qRegisterMetaTypeStreamOperators<OBSSceneItem>("OBSSceneItem");
254

P
Palana 已提交
255 256 257
	ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false);
	ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false);

V
VodBox 已提交
258 259 260 261
	bool sceneGrid = config_get_bool(App()->GlobalConfig(), "BasicWindow",
					 "gridMode");
	ui->scenes->SetGridMode(sceneGrid);

262 263
	ui->scenes->setItemDelegate(new SceneRenameDelegate(ui->scenes));

264
	auto displayResize = [this]() {
265 266 267 268
		struct obs_video_info ovi;

		if (obs_get_video_info(&ovi))
			ResizePreview(ovi.base_width, ovi.base_height);
269 270 271 272
	};

	connect(windowHandle(), &QWindow::screenChanged, displayResize);
	connect(ui->preview, &OBSQTDisplay::DisplayResized, displayResize);
J
jp9000 已提交
273

274 275
	delete shortcutFilter;
	shortcutFilter = CreateShortcutFilter();
P
pkv 已提交
276
	installEventFilter(shortcutFilter);
P
Palana 已提交
277

278
	stringstream name;
J
jp9000 已提交
279
	name << "OBS " << App()->GetVersionString();
280 281 282
	blog(LOG_INFO, "%s", name.str().c_str());
	blog(LOG_INFO, "---------------------------------");

283
	UpdateTitleBar();
J
jp9000 已提交
284 285

	connect(ui->scenes->itemDelegate(),
J
jp9000 已提交
286 287 288 289 290
		SIGNAL(closeEditor(QWidget *,
				   QAbstractItemDelegate::EndEditHint)),
		this,
		SLOT(SceneNameEdited(QWidget *,
				     QAbstractItemDelegate::EndEditHint)));
J
jp9000 已提交
291

292
	cpuUsageInfo = os_cpu_usage_info_start();
J
jp9000 已提交
293
	cpuUsageTimer = new QTimer(this);
J
jp9000 已提交
294 295
	connect(cpuUsageTimer.data(), SIGNAL(timeout()), ui->statusbar,
		SLOT(UpdateCPUUsage()));
J
jp9000 已提交
296
	cpuUsageTimer->start(3000);
297

298 299 300 301
	diskFullTimer = new QTimer(this);
	connect(diskFullTimer, SIGNAL(timeout()), this,
		SLOT(CheckDiskSpaceRemaining()));

S
Shaolin 已提交
302 303 304 305 306 307 308 309
	QAction *renameScene = new QAction(ui->scenesDock);
	renameScene->setShortcutContext(Qt::WidgetWithChildrenShortcut);
	connect(renameScene, SIGNAL(triggered()), this, SLOT(EditSceneName()));
	ui->scenesDock->addAction(renameScene);

	QAction *renameSource = new QAction(ui->sourcesDock);
	renameSource->setShortcutContext(Qt::WidgetWithChildrenShortcut);
	connect(renameSource, SIGNAL(triggered()), this,
J
jp9000 已提交
310
		SLOT(EditSceneItemName()));
S
Shaolin 已提交
311 312
	ui->sourcesDock->addAction(renameSource);

313
#ifdef __APPLE__
S
Shaolin 已提交
314 315 316
	renameScene->setShortcut({Qt::Key_Return});
	renameSource->setShortcut({Qt::Key_Return});

317 318
	ui->actionRemoveSource->setShortcuts({Qt::Key_Backspace});
	ui->actionRemoveScene->setShortcuts({Qt::Key_Backspace});
319 320 321

	ui->action_Settings->setMenuRole(QAction::PreferencesRole);
	ui->actionE_xit->setMenuRole(QAction::QuitRole);
S
Shaolin 已提交
322 323 324
#else
	renameScene->setShortcut({Qt::Key_F2});
	renameSource->setShortcut({Qt::Key_F2});
325
#endif
326

J
jp9000 已提交
327
	auto addNudge = [this](const QKeySequence &seq, const char *s) {
328 329 330 331 332 333 334 335 336 337 338
		QAction *nudge = new QAction(ui->preview);
		nudge->setShortcut(seq);
		nudge->setShortcutContext(Qt::WidgetShortcut);
		ui->preview->addAction(nudge);
		connect(nudge, SIGNAL(triggered()), this, s);
	};

	addNudge(Qt::Key_Up, SLOT(NudgeUp()));
	addNudge(Qt::Key_Down, SLOT(NudgeDown()));
	addNudge(Qt::Key_Left, SLOT(NudgeLeft()));
	addNudge(Qt::Key_Right, SLOT(NudgeRight()));
J
jp9000 已提交
339 340 341 342 343 344

	assignDockToggle(ui->scenesDock, ui->toggleScenes);
	assignDockToggle(ui->sourcesDock, ui->toggleSources);
	assignDockToggle(ui->mixerDock, ui->toggleMixer);
	assignDockToggle(ui->transitionsDock, ui->toggleTransitions);
	assignDockToggle(ui->controlsDock, ui->toggleControls);
345
	assignDockToggle(statsDock, ui->toggleStats);
S
SuslikV 已提交
346 347 348 349 350 351 352

	//hide all docking panes
	ui->toggleScenes->setChecked(false);
	ui->toggleSources->setChecked(false);
	ui->toggleMixer->setChecked(false);
	ui->toggleTransitions->setChecked(false);
	ui->toggleControls->setChecked(false);
A
Alex Anderson 已提交
353
	ui->toggleStats->setChecked(false);
S
SuslikV 已提交
354

355 356
	QPoint curPos;

S
SuslikV 已提交
357 358
	//restore parent window geometry
	const char *geometry = config_get_string(App()->GlobalConfig(),
J
jp9000 已提交
359
						 "BasicWindow", "geometry");
S
SuslikV 已提交
360
	if (geometry != NULL) {
J
jp9000 已提交
361 362
		QByteArray byteArray =
			QByteArray::fromBase64(QByteArray(geometry));
S
SuslikV 已提交
363 364 365 366 367
		restoreGeometry(byteArray);

		QRect windowGeometry = normalGeometry();
		if (!WindowPositionValid(windowGeometry)) {
			QRect rect = App()->desktop()->geometry();
J
jp9000 已提交
368 369 370
			setGeometry(QStyle::alignedRect(Qt::LeftToRight,
							Qt::AlignCenter, size(),
							rect));
S
SuslikV 已提交
371
		}
372 373 374

		curPos = pos();
	} else {
J
jp9000 已提交
375 376
		QRect desktopRect =
			QGuiApplication::primaryScreen()->geometry();
377 378
		QSize adjSize = desktopRect.size() / 2 - size() / 2;
		curPos = QPoint(adjSize.width(), adjSize.height());
S
SuslikV 已提交
379
	}
380 381 382 383 384 385

	QPoint curSize(width(), height());
	QPoint statsDockSize(statsDock->width(), statsDock->height());
	QPoint statsDockPos = curSize / 2 - statsDockSize / 2;
	QPoint newPos = curPos + statsDockPos;
	statsDock->move(newPos);
386 387

	ui->previewLabel->setProperty("themeID", "previewProgramLabels");
K
Kurt Kartaltepe 已提交
388
	ui->previewLabel->style()->polish(ui->previewLabel);
389

J
jp9000 已提交
390 391
	bool labels = config_get_bool(GetGlobalConfig(), "BasicWindow",
				      "StudioModeLabels");
392 393 394 395 396

	if (!previewProgramMode)
		ui->previewLabel->setHidden(true);
	else
		ui->previewLabel->setHidden(!labels);
397 398 399 400 401 402 403

	ui->previewDisabledWidget->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(ui->previewDisabledWidget,
		SIGNAL(customContextMenuRequested(const QPoint &)), this,
		SLOT(PreviewDisabledMenu(const QPoint &)));
	connect(ui->enablePreviewButton, SIGNAL(clicked()), this,
		SLOT(TogglePreview()));
404 405 406 407 408 409

	connect(ui->scenes->model(),
		SIGNAL(rowsMoved(QModelIndex, int, int, QModelIndex, int)),
		this,
		SLOT(ScenesReordered(const QModelIndex &, int, int,
				     const QModelIndex &, int)));
410 411
}

412
static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent,
J
jp9000 已提交
413
			    vector<OBSSource> &audioSources)
414
{
415
	obs_source_t *source = obs_get_output_source(channel);
416 417 418
	if (!source)
		return;

419 420
	audioSources.push_back(source);

421
	obs_data_t *data = obs_save_source(source);
422

J
jp9000 已提交
423
	obs_data_set_obj(parent, name, data);
424 425 426 427 428

	obs_data_release(data);
	obs_source_release(source);
}

429
static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder,
J
jp9000 已提交
430 431 432 433 434
				    obs_data_array_t *quickTransitionData,
				    int transitionDuration,
				    obs_data_array_t *transitions,
				    OBSScene &scene, OBSSource &curProgramScene,
				    obs_data_array_t *savedProjectorList)
435
{
436 437 438
	obs_data_t *saveData = obs_data_create();

	vector<OBSSource> audioSources;
439
	audioSources.reserve(6);
440 441 442

	SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
	SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
J
jp9000 已提交
443 444 445 446
	SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
	SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
	SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
	SaveAudioDevice(AUX_AUDIO_4, 6, saveData, audioSources);
447

448 449 450
	/* -------------------------------- */
	/* save non-group sources           */

J
jp9000 已提交
451
	auto FilterAudioSources = [&](obs_source_t *source) {
452 453 454
		if (obs_source_is_group(source))
			return false;

455
		return find(begin(audioSources), end(audioSources), source) ==
J
jp9000 已提交
456
		       end(audioSources);
457 458 459 460
	};
	using FilterAudioSources_t = decltype(FilterAudioSources);

	obs_data_array_t *sourcesArray = obs_save_sources_filtered(
J
jp9000 已提交
461 462 463 464 465
		[](void *data, obs_source_t *source) {
			return (*static_cast<FilterAudioSources_t *>(data))(
				source);
		},
		static_cast<void *>(&FilterAudioSources));
466

467 468 469 470 471
	/* -------------------------------- */
	/* save group sources separately    */

	/* saving separately ensures they won't be loaded in older versions */
	obs_data_array_t *groupsArray = obs_save_sources_filtered(
J
jp9000 已提交
472 473 474 475
		[](void *, obs_source_t *source) {
			return obs_source_is_group(source);
		},
		nullptr);
476 477 478

	/* -------------------------------- */

479 480
	obs_source_t *transition = obs_get_output_source(0);
	obs_source_t *currentScene = obs_scene_get_source(scene);
J
jp9000 已提交
481 482
	const char *sceneName = obs_source_get_name(currentScene);
	const char *programName = obs_source_get_name(curProgramScene);
483

J
jp9000 已提交
484 485
	const char *sceneCollection = config_get_string(
		App()->GlobalConfig(), "Basic", "SceneCollection");
J
jp9000 已提交
486

J
jp9000 已提交
487
	obs_data_set_string(saveData, "current_scene", sceneName);
488
	obs_data_set_string(saveData, "current_program_scene", programName);
J
jp9000 已提交
489
	obs_data_set_array(saveData, "scene_order", sceneOrder);
J
jp9000 已提交
490
	obs_data_set_string(saveData, "name", sceneCollection);
J
jp9000 已提交
491
	obs_data_set_array(saveData, "sources", sourcesArray);
492
	obs_data_set_array(saveData, "groups", groupsArray);
493
	obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
J
jp9000 已提交
494
	obs_data_set_array(saveData, "transitions", transitions);
C
cg2121 已提交
495
	obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
496
	obs_data_array_release(sourcesArray);
497
	obs_data_array_release(groupsArray);
498 499

	obs_data_set_string(saveData, "current_transition",
J
jp9000 已提交
500
			    obs_source_get_name(transition));
501 502
	obs_data_set_int(saveData, "transition_duration", transitionDuration);
	obs_source_release(transition);
503 504 505 506

	return saveData;
}

S
Socapex 已提交
507 508 509 510
void OBSBasic::copyActionsDynamicProperties()
{
	// Themes need the QAction dynamic properties
	for (QAction *x : ui->scenesToolbar->actions()) {
J
jp9000 已提交
511
		QWidget *temp = ui->scenesToolbar->widgetForAction(x);
S
Socapex 已提交
512 513 514 515 516 517 518

		for (QByteArray &y : x->dynamicPropertyNames()) {
			temp->setProperty(y, x->property(y));
		}
	}

	for (QAction *x : ui->sourcesToolbar->actions()) {
J
jp9000 已提交
519
		QWidget *temp = ui->sourcesToolbar->widgetForAction(x);
S
Socapex 已提交
520 521 522 523 524 525 526

		for (QByteArray &y : x->dynamicPropertyNames()) {
			temp->setProperty(y, x->property(y));
		}
	}
}

S
Shaolin 已提交
527 528
void OBSBasic::UpdateVolumeControlsDecayRate()
{
J
jp9000 已提交
529 530
	double meterDecayRate =
		config_get_double(basicConfig, "Audio", "MeterDecayRate");
S
Shaolin 已提交
531 532 533 534 535 536

	for (size_t i = 0; i < volumes.size(); i++) {
		volumes[i]->SetMeterDecayRate(meterDecayRate);
	}
}

537 538
void OBSBasic::UpdateVolumeControlsPeakMeterType()
{
J
jp9000 已提交
539 540
	uint32_t peakMeterTypeIdx =
		config_get_uint(basicConfig, "Audio", "PeakMeterType");
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559

	enum obs_peak_meter_type peakMeterType;
	switch (peakMeterTypeIdx) {
	case 0:
		peakMeterType = SAMPLE_PEAK_METER;
		break;
	case 1:
		peakMeterType = TRUE_PEAK_METER;
		break;
	default:
		peakMeterType = SAMPLE_PEAK_METER;
		break;
	}

	for (size_t i = 0; i < volumes.size(); i++) {
		volumes[i]->setPeakMeterType(peakMeterType);
	}
}

560 561
void OBSBasic::ClearVolumeControls()
{
C
craftwar 已提交
562 563
	for (VolControl *vol : volumes)
		delete vol;
564 565 566 567

	volumes.clear();
}

J
jp9000 已提交
568 569 570 571 572 573 574
obs_data_array_t *OBSBasic::SaveSceneListOrder()
{
	obs_data_array_t *sceneOrder = obs_data_array_create();

	for (int i = 0; i < ui->scenes->count(); i++) {
		obs_data_t *data = obs_data_create();
		obs_data_set_string(data, "name",
J
jp9000 已提交
575
				    QT_TO_UTF8(ui->scenes->item(i)->text()));
J
jp9000 已提交
576 577 578 579 580 581 582
		obs_data_array_push_back(sceneOrder, data);
		obs_data_release(data);
	}

	return sceneOrder;
}

C
cg2121 已提交
583 584
obs_data_array_t *OBSBasic::SaveProjectors()
{
585
	obs_data_array_t *savedProjectors = obs_data_array_create();
C
cg2121 已提交
586

587 588 589
	auto saveProjector = [savedProjectors](OBSProjector *projector) {
		if (!projector)
			return;
R
Ryan Foster 已提交
590 591

		obs_data_t *data = obs_data_create();
592
		ProjectorType type = projector->GetProjectorType();
S
Shaolin 已提交
593 594 595 596 597 598 599 600 601 602 603
		switch (type) {
		case ProjectorType::Scene:
		case ProjectorType::Source: {
			obs_source_t *source = projector->GetSource();
			const char *name = obs_source_get_name(source);
			obs_data_set_string(data, "name", name);
			break;
		}
		default:
			break;
		}
604 605
		obs_data_set_int(data, "monitor", projector->GetMonitor());
		obs_data_set_int(data, "type", static_cast<int>(type));
J
jp9000 已提交
606 607 608
		obs_data_set_string(
			data, "geometry",
			projector->saveGeometry().toBase64().constData());
609
		obs_data_array_push_back(savedProjectors, data);
R
Ryan Foster 已提交
610
		obs_data_release(data);
611
	};
R
Ryan Foster 已提交
612

613 614
	for (size_t i = 0; i < projectors.size(); i++)
		saveProjector(static_cast<OBSProjector *>(projectors[i]));
S
Shaolin 已提交
615

616
	return savedProjectors;
S
Shaolin 已提交
617 618
}

619 620
void OBSBasic::Save(const char *file)
{
621 622 623 624 625
	OBSScene scene = GetCurrentScene();
	OBSSource curProgramScene = OBSGetStrongRef(programScene);
	if (!curProgramScene)
		curProgramScene = obs_scene_get_source(scene);

J
jp9000 已提交
626
	obs_data_array_t *sceneOrder = SaveSceneListOrder();
J
jp9000 已提交
627
	obs_data_array_t *transitions = SaveTransitions();
628
	obs_data_array_t *quickTrData = SaveQuickTransitions();
C
cg2121 已提交
629
	obs_data_array_t *savedProjectorList = SaveProjectors();
J
jp9000 已提交
630 631 632
	obs_data_t *saveData = GenerateSaveData(
		sceneOrder, quickTrData, ui->transitionDuration->value(),
		transitions, scene, curProgramScene, savedProjectorList);
633

J
jp9000 已提交
634
	obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
635
	obs_data_set_bool(saveData, "scaling_enabled",
J
jp9000 已提交
636
			  ui->preview->IsFixedScaling());
637
	obs_data_set_int(saveData, "scaling_level",
J
jp9000 已提交
638
			 ui->preview->GetScalingLevel());
639
	obs_data_set_double(saveData, "scaling_off_x",
J
jp9000 已提交
640
			    ui->preview->GetScrollX());
641
	obs_data_set_double(saveData, "scaling_off_y",
J
jp9000 已提交
642
			    ui->preview->GetScrollY());
J
jp9000 已提交
643

J
jp9000 已提交
644 645 646 647 648 649 650
	if (api) {
		obs_data_t *moduleObj = obs_data_create();
		api->on_save(moduleObj);
		obs_data_set_obj(saveData, "modules", moduleObj);
		obs_data_release(moduleObj);
	}

651 652
	if (!obs_data_save_json_safe(saveData, file, "tmp", "bak"))
		blog(LOG_ERROR, "Could not save scene data to %s", file);
653 654

	obs_data_release(saveData);
J
jp9000 已提交
655
	obs_data_array_release(sceneOrder);
656
	obs_data_array_release(quickTrData);
J
jp9000 已提交
657
	obs_data_array_release(transitions);
C
cg2121 已提交
658
	obs_data_array_release(savedProjectorList);
659 660
}

I
Ilya M 已提交
661 662 663 664 665 666 667 668 669 670 671 672 673
void OBSBasic::DeferSaveBegin()
{
	os_atomic_inc_long(&disableSaving);
}

void OBSBasic::DeferSaveEnd()
{
	long result = os_atomic_dec_long(&disableSaving);
	if (result == 0) {
		SaveProject();
	}
}

674 675
static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val);

676
static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
677
{
678
	obs_data_t *data = obs_data_get_obj(parent, name);
679 680 681
	if (!data)
		return;

682
	obs_source_t *source = obs_load_source(data);
683 684
	if (source) {
		obs_set_output_source(channel, source);
685 686 687 688

		const char *name = obs_source_get_name(source);
		blog(LOG_INFO, "[Loaded global audio device]: '%s'", name);
		obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
689 690 691 692 693 694
		obs_source_release(source);
	}

	obs_data_release(data);
}

695 696 697
static inline bool HasAudioDevices(const char *source_id)
{
	const char *output_id = source_id;
698
	obs_properties_t *props = obs_get_source_properties(output_id);
699 700 701 702 703 704 705 706 707 708 709 710 711 712
	size_t count = 0;

	if (!props)
		return false;

	obs_property_t *devices = obs_properties_get(props, "device_id");
	if (devices)
		count = obs_property_list_item_count(devices);

	obs_properties_destroy(props);

	return count != 0;
}

713
void OBSBasic::CreateFirstRunSources()
714
{
715
	bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
J
jp9000 已提交
716
	bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
717 718 719

	if (hasDesktopAudio)
		ResetAudioDevice(App()->OutputAudioSource(), "default",
J
jp9000 已提交
720
				 Str("Basic.DesktopDevice1"), 1);
721 722
	if (hasInputAudio)
		ResetAudioDevice(App()->InputAudioSource(), "default",
J
jp9000 已提交
723
				 Str("Basic.AuxDevice1"), 3);
724 725
}

726
void OBSBasic::CreateDefaultScene(bool firstStart)
727 728 729 730
{
	disableSaving++;

	ClearSceneData();
731 732 733 734
	InitDefaultTransitions();
	CreateDefaultQuickTransitions();
	ui->transitionDuration->setValue(300);
	SetTransition(fadeTransition);
735

J
jp9000 已提交
736
	obs_scene_t *scene = obs_scene_create(Str("Basic.Scene"));
737

738
	if (firstStart)
739
		CreateFirstRunSources();
740

741
	SetCurrentScene(scene, true);
742
	obs_scene_release(scene);
J
jp9000 已提交
743 744

	disableSaving--;
745 746
}

J
jp9000 已提交
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775
static void ReorderItemByName(QListWidget *lw, const char *name, int newIndex)
{
	for (int i = 0; i < lw->count(); i++) {
		QListWidgetItem *item = lw->item(i);

		if (strcmp(name, QT_TO_UTF8(item->text())) == 0) {
			if (newIndex != i) {
				item = lw->takeItem(i);
				lw->insertItem(newIndex, item);
			}
			break;
		}
	}
}

void OBSBasic::LoadSceneListOrder(obs_data_array_t *array)
{
	size_t num = obs_data_array_count(array);

	for (size_t i = 0; i < num; i++) {
		obs_data_t *data = obs_data_array_item(array, i);
		const char *name = obs_data_get_string(data, "name");

		ReorderItemByName(ui->scenes, name, (int)i);

		obs_data_release(data);
	}
}

C
cg2121 已提交
776 777
void OBSBasic::LoadSavedProjectors(obs_data_array_t *array)
{
778 779 780 781 782
	for (SavedProjectorInfo *info : savedProjectorsArray) {
		delete info;
	}
	savedProjectorsArray.clear();

C
cg2121 已提交
783 784 785 786 787
	size_t num = obs_data_array_count(array);

	for (size_t i = 0; i < num; i++) {
		obs_data_t *data = obs_data_array_item(array, i);

788 789
		SavedProjectorInfo *info = new SavedProjectorInfo();
		info->monitor = obs_data_get_int(data, "monitor");
J
jp9000 已提交
790 791 792 793
		info->type = static_cast<ProjectorType>(
			obs_data_get_int(data, "type"));
		info->geometry =
			std::string(obs_data_get_string(data, "geometry"));
S
Shaolin 已提交
794
		info->name = std::string(obs_data_get_string(data, "name"));
795
		savedProjectorsArray.emplace_back(info);
S
Shaolin 已提交
796 797 798 799 800

		obs_data_release(data);
	}
}

J
jp9000 已提交
801
static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val)
802 803 804 805 806 807 808 809 810 811 812 813
{
	const char *name = obs_source_get_name(filter);
	const char *id = obs_source_get_id(filter);
	int val = (int)(intptr_t)v_val;
	string indent;

	for (int i = 0; i < val; i++)
		indent += "    ";

	blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
}

J
jp9000 已提交
814
static bool LogSceneItem(obs_scene_t *, obs_sceneitem_t *item, void *v_val)
815 816 817 818
{
	obs_source_t *source = obs_sceneitem_get_source(item);
	const char *name = obs_source_get_name(source);
	const char *id = obs_source_get_id(source);
M
Matt Gajownik 已提交
819 820 821 822 823
	int indent_count = (int)(intptr_t)v_val;
	string indent;

	for (int i = 0; i < indent_count; i++)
		indent += "    ";
824

M
Matt Gajownik 已提交
825
	blog(LOG_INFO, "%s- source: '%s' (%s)", indent.c_str(), name, id);
826

827 828 829 830 831 832
	obs_monitoring_type monitoring_type =
		obs_source_get_monitoring_type(source);

	if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
		const char *type =
			(monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY)
J
jp9000 已提交
833 834
				? "monitor only"
				: "monitor and output";
835

M
Matt Gajownik 已提交
836
		blog(LOG_INFO, "    %s- monitoring: %s", indent.c_str(), type);
837
	}
M
Matt Gajownik 已提交
838
	int child_indent = 1 + indent_count;
J
jp9000 已提交
839 840
	obs_source_enum_filters(source, LogFilter,
				(void *)(intptr_t)child_indent);
M
Matt Gajownik 已提交
841
	if (obs_sceneitem_is_group(item))
J
jp9000 已提交
842 843
		obs_sceneitem_group_enum_items(item, LogSceneItem,
					       (void *)(intptr_t)child_indent);
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
	return true;
}

void OBSBasic::LogScenes()
{
	blog(LOG_INFO, "------------------------------------------------");
	blog(LOG_INFO, "Loaded scenes:");

	for (int i = 0; i < ui->scenes->count(); i++) {
		QListWidgetItem *item = ui->scenes->item(i);
		OBSScene scene = GetOBSRef<OBSScene>(item);

		obs_source_t *source = obs_scene_get_source(scene);
		const char *name = obs_source_get_name(source);

		blog(LOG_INFO, "- scene '%s':", name);
J
jp9000 已提交
860 861
		obs_scene_enum_items(scene, LogSceneItem, (void *)(intptr_t)1);
		obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
862 863 864 865 866
	}

	blog(LOG_INFO, "------------------------------------------------");
}

867 868
void OBSBasic::Load(const char *file)
{
869 870 871 872 873
	disableSaving++;

	obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
	if (!data) {
		disableSaving--;
874
		blog(LOG_INFO, "No scene file found, creating default scene");
875
		CreateDefaultScene(true);
J
jp9000 已提交
876
		SaveProject();
877
		return;
878
	}
879

880
	ClearSceneData();
881
	InitDefaultTransitions();
882

883 884 885 886
	obs_data_t *modulesObj = obs_data_get_obj(data, "modules");
	if (api)
		api->on_preload(modulesObj);

J
jp9000 已提交
887
	obs_data_array_t *sceneOrder = obs_data_get_array(data, "scene_order");
J
jp9000 已提交
888 889 890 891 892 893 894 895
	obs_data_array_t *sources = obs_data_get_array(data, "sources");
	obs_data_array_t *groups = obs_data_get_array(data, "groups");
	obs_data_array_t *transitions = obs_data_get_array(data, "transitions");
	const char *sceneName = obs_data_get_string(data, "current_scene");
	const char *programSceneName =
		obs_data_get_string(data, "current_program_scene");
	const char *transitionName =
		obs_data_get_string(data, "current_transition");
896

897 898 899 900 901 902
	if (!opt_starting_scene.empty()) {
		programSceneName = opt_starting_scene.c_str();
		if (!IsPreviewProgramMode())
			sceneName = opt_starting_scene.c_str();
	}

903 904 905 906 907 908
	int newDuration = obs_data_get_int(data, "transition_duration");
	if (!newDuration)
		newDuration = 300;

	if (!transitionName)
		transitionName = obs_source_get_name(fadeTransition);
J
jp9000 已提交
909 910

	const char *curSceneCollection = config_get_string(
J
jp9000 已提交
911
		App()->GlobalConfig(), "Basic", "SceneCollection");
J
jp9000 已提交
912 913 914

	obs_data_set_default_string(data, "name", curSceneCollection);

J
jp9000 已提交
915 916 917 918
	const char *name = obs_data_get_string(data, "name");
	obs_source_t *curScene;
	obs_source_t *curProgramScene;
	obs_source_t *curTransition;
919

J
jp9000 已提交
920 921 922
	if (!name || !*name)
		name = curSceneCollection;

923 924
	LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
	LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
J
jp9000 已提交
925 926 927 928
	LoadAudioDevice(AUX_AUDIO_1, 3, data);
	LoadAudioDevice(AUX_AUDIO_2, 4, data);
	LoadAudioDevice(AUX_AUDIO_3, 5, data);
	LoadAudioDevice(AUX_AUDIO_4, 6, data);
929

930 931 932 933 934 935 936
	if (!sources) {
		sources = groups;
		groups = nullptr;
	} else {
		obs_data_array_push_back_array(sources, groups);
	}

937
	obs_load_sources(sources, nullptr, nullptr);
938

J
jp9000 已提交
939 940
	if (transitions)
		LoadTransitions(transitions);
J
jp9000 已提交
941 942 943
	if (sceneOrder)
		LoadSceneListOrder(sceneOrder);

J
jp9000 已提交
944 945
	obs_data_array_release(transitions);

946 947 948 949 950 951 952
	curTransition = FindTransition(transitionName);
	if (!curTransition)
		curTransition = fadeTransition;

	ui->transitionDuration->setValue(newDuration);
	SetTransition(curTransition);

953
retryScene:
954
	curScene = obs_get_source_by_name(sceneName);
955
	curProgramScene = obs_get_source_by_name(programSceneName);
956 957 958 959 960

	/* if the starting scene command line parameter is bad at all,
	 * fall back to original settings */
	if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
		sceneName = obs_data_get_string(data, "current_scene");
J
jp9000 已提交
961 962
		programSceneName =
			obs_data_get_string(data, "current_program_scene");
963 964 965 966 967 968
		obs_source_release(curScene);
		obs_source_release(curProgramScene);
		opt_starting_scene.clear();
		goto retryScene;
	}

969 970 971 972 973 974 975 976
	if (!curProgramScene) {
		curProgramScene = curScene;
		obs_source_addref(curScene);
	}

	SetCurrentScene(curScene, true);
	if (IsPreviewProgramMode())
		TransitionToScene(curProgramScene, true);
977
	obs_source_release(curScene);
978
	obs_source_release(curProgramScene);
979 980

	obs_data_array_release(sources);
981
	obs_data_array_release(groups);
J
jp9000 已提交
982
	obs_data_array_release(sceneOrder);
J
jp9000 已提交
983

984 985 986
	/* ------------------- */

	bool projectorSave = config_get_bool(GetGlobalConfig(), "BasicWindow",
J
jp9000 已提交
987
					     "SaveProjectors");
988 989

	if (projectorSave) {
J
jp9000 已提交
990 991
		obs_data_array_t *savedProjectors =
			obs_data_get_array(data, "saved_projectors");
992

993
		if (savedProjectors) {
994
			LoadSavedProjectors(savedProjectors);
995 996 997
			OpenSavedProjectors();
			activateWindow();
		}
998 999 1000 1001 1002 1003

		obs_data_array_release(savedProjectors);
	}

	/* ------------------- */

J
jp9000 已提交
1004 1005 1006 1007
	std::string file_base = strrchr(file, '/') + 1;
	file_base.erase(file_base.size() - 5, 5);

	config_set_string(App()->GlobalConfig(), "Basic", "SceneCollection",
J
jp9000 已提交
1008
			  name);
J
jp9000 已提交
1009
	config_set_string(App()->GlobalConfig(), "Basic", "SceneCollectionFile",
J
jp9000 已提交
1010
			  file_base.c_str());
J
jp9000 已提交
1011

J
jp9000 已提交
1012 1013
	obs_data_array_t *quickTransitionData =
		obs_data_get_array(data, "quick_transitions");
1014 1015 1016 1017 1018
	LoadQuickTransitions(quickTransitionData);
	obs_data_array_release(quickTransitionData);

	RefreshQuickTransitions();

J
jp9000 已提交
1019 1020 1021 1022
	bool previewLocked = obs_data_get_bool(data, "preview_locked");
	ui->preview->SetLocked(previewLocked);
	ui->actionLockPreview->setChecked(previewLocked);

1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
	/* ---------------------- */

	bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
	int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
	float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
	float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");

	if (fixedScaling) {
		ui->preview->SetScalingLevel(scalingLevel);
		ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
J
Joseph El-Khouri 已提交
1033
	}
1034
	ui->preview->SetFixedScaling(fixedScaling);
1035
	emit ui->preview->DisplayResized();
J
Joseph El-Khouri 已提交
1036

1037
	/* ---------------------- */
J
Joseph El-Khouri 已提交
1038

1039
	if (api)
J
jp9000 已提交
1040 1041
		api->on_load(modulesObj);

1042
	obs_data_release(modulesObj);
1043
	obs_data_release(data);
J
jp9000 已提交
1044

1045 1046 1047
	if (!opt_starting_scene.empty())
		opt_starting_scene.clear();

1048
	if (opt_start_streaming) {
1049
		blog(LOG_INFO, "Starting stream due to command line parameter");
1050
		QMetaObject::invokeMethod(this, "StartStreaming",
J
jp9000 已提交
1051
					  Qt::QueuedConnection);
1052 1053 1054 1055
		opt_start_streaming = false;
	}

	if (opt_start_recording) {
J
jp9000 已提交
1056 1057
		blog(LOG_INFO,
		     "Starting recording due to command line parameter");
1058
		QMetaObject::invokeMethod(this, "StartRecording",
J
jp9000 已提交
1059
					  Qt::QueuedConnection);
1060 1061 1062
		opt_start_recording = false;
	}

C
cg2121 已提交
1063 1064
	if (opt_start_replaybuffer) {
		QMetaObject::invokeMethod(this, "StartReplayBuffer",
J
jp9000 已提交
1065
					  Qt::QueuedConnection);
C
cg2121 已提交
1066 1067 1068
		opt_start_replaybuffer = false;
	}

1069
	copyStrings.clear();
1070 1071
	copyFiltersString = nullptr;

1072 1073
	LogScenes();

J
jp9000 已提交
1074
	disableSaving--;
1075

1076
	if (api) {
1077
		api->on_event(OBS_FRONTEND_EVENT_SCENE_CHANGED);
1078 1079
		api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
	}
1080 1081
}

J
jp9000 已提交
1082
#define SERVICE_PATH "service.json"
1083 1084 1085 1086 1087 1088

void OBSBasic::SaveService()
{
	if (!service)
		return;

1089
	char serviceJsonPath[512];
J
jp9000 已提交
1090
	int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
J
jp9000 已提交
1091
				 SERVICE_PATH);
1092
	if (ret <= 0)
1093 1094
		return;

J
jp9000 已提交
1095
	obs_data_t *data = obs_data_create();
1096
	obs_data_t *settings = obs_service_get_settings(service);
1097

1098
	obs_data_set_string(data, "type", obs_service_get_type(service));
J
jp9000 已提交
1099
	obs_data_set_obj(data, "settings", settings);
1100

1101 1102
	if (!obs_data_save_json_safe(data, serviceJsonPath, "tmp", "bak"))
		blog(LOG_WARNING, "Failed to save service");
1103 1104 1105 1106 1107 1108 1109 1110 1111

	obs_data_release(settings);
	obs_data_release(data);
}

bool OBSBasic::LoadService()
{
	const char *type;

1112
	char serviceJsonPath[512];
J
jp9000 已提交
1113
	int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
J
jp9000 已提交
1114
				 SERVICE_PATH);
1115
	if (ret <= 0)
1116 1117
		return false;

J
jp9000 已提交
1118 1119
	obs_data_t *data =
		obs_data_create_from_json_file_safe(serviceJsonPath, "bak");
1120

1121 1122 1123
	if (!data)
		return false;

1124
	obs_data_set_default_string(data, "type", "rtmp_common");
J
jp9000 已提交
1125
	type = obs_data_get_string(data, "type");
1126

1127
	obs_data_t *settings = obs_data_get_obj(data, "settings");
P
Palana 已提交
1128
	obs_data_t *hotkey_data = obs_data_get_obj(data, "hotkeys");
1129

1130
	service = obs_service_create(type, "default_service", settings,
J
jp9000 已提交
1131
				     hotkey_data);
1132
	obs_service_release(service);
1133

P
Palana 已提交
1134
	obs_data_release(hotkey_data);
1135 1136 1137 1138 1139 1140 1141 1142
	obs_data_release(settings);
	obs_data_release(data);

	return !!service;
}

bool OBSBasic::InitService()
{
P
Palana 已提交
1143 1144
	ProfileScope("OBSBasic::InitService");

1145 1146 1147
	if (LoadService())
		return true;

1148
	service = obs_service_create("rtmp_common", "default_service", nullptr,
J
jp9000 已提交
1149
				     nullptr);
1150 1151
	if (!service)
		return false;
1152
	obs_service_release(service);
1153 1154 1155 1156

	return true;
}

J
jp9000 已提交
1157 1158 1159
static const double scaled_vals[] = {1.0,         1.25, (1.0 / 0.75), 1.5,
				     (1.0 / 0.6), 1.75, 2.0,          2.25,
				     2.5,         2.75, 3.0,          0.0};
1160

1161 1162
extern void CheckExistingCookieId();

1163 1164
bool OBSBasic::InitBasicConfigDefaults()
{
J
jp9000 已提交
1165
	QList<QScreen *> screens = QGuiApplication::screens();
1166

1167
	if (!screens.size()) {
1168
		OBSErrorBox(NULL, "There appears to be no monitors.  Er, this "
J
jp9000 已提交
1169
				  "technically shouldn't be possible.");
1170 1171 1172
		return false;
	}

1173 1174 1175 1176
	QScreen *primaryScreen = QGuiApplication::primaryScreen();

	uint32_t cx = primaryScreen->size().width();
	uint32_t cy = primaryScreen->size().height();
1177

J
jp9000 已提交
1178 1179
	bool oldResolutionDefaults = config_get_bool(
		App()->GlobalConfig(), "General", "Pre19Defaults");
1180 1181 1182 1183 1184 1185 1186 1187 1188

	/* use 1920x1080 for new default base res if main monitor is above
	 * 1920x1080, but don't apply for people from older builds -- only to
	 * new users */
	if (!oldResolutionDefaults && (cx * cy) > (1920 * 1080)) {
		cx = 1920;
		cy = 1080;
	}

P
pkviet 已提交
1189 1190 1191 1192 1193 1194 1195 1196
	bool changed = false;

	/* ----------------------------------------------------- */
	/* move over old FFmpeg track settings                   */
	if (config_has_user_value(basicConfig, "AdvOut", "FFAudioTrack") &&
	    !config_has_user_value(basicConfig, "AdvOut", "Pre22.1Settings")) {

		int track = (int)config_get_int(basicConfig, "AdvOut",
J
jp9000 已提交
1197
						"FFAudioTrack");
P
pkviet 已提交
1198
		config_set_int(basicConfig, "AdvOut", "FFAudioMixes",
J
jp9000 已提交
1199
			       1LL << (track - 1));
P
pkviet 已提交
1200 1201 1202 1203
		config_set_bool(basicConfig, "AdvOut", "Pre22.1Settings", true);
		changed = true;
	}

1204 1205 1206 1207 1208
	/* ----------------------------------------------------- */
	/* move over mixer values in advanced if older config */
	if (config_has_user_value(basicConfig, "AdvOut", "RecTrackIndex") &&
	    !config_has_user_value(basicConfig, "AdvOut", "RecTracks")) {

J
jp9000 已提交
1209 1210
		uint64_t track =
			config_get_uint(basicConfig, "AdvOut", "RecTrackIndex");
1211 1212 1213
		track = 1ULL << (track - 1);
		config_set_uint(basicConfig, "AdvOut", "RecTracks", track);
		config_remove_value(basicConfig, "AdvOut", "RecTrackIndex");
P
pkviet 已提交
1214
		changed = true;
1215 1216
	}

1217 1218 1219 1220 1221 1222 1223 1224 1225
	/* ----------------------------------------------------- */
	/* set twitch chat extensions to "both" if prev version  */
	/* is under 24.1                                         */
	if (config_get_bool(GetGlobalConfig(), "General", "Pre24.1Defaults") &&
	    !config_has_user_value(basicConfig, "Twitch", "AddonChoice")) {
		config_set_int(basicConfig, "Twitch", "AddonChoice", 3);
		changed = true;
	}

1226 1227
	/* ----------------------------------------------------- */

P
pkviet 已提交
1228 1229 1230 1231 1232
	if (changed)
		config_save_safe(basicConfig, "tmp", nullptr);

	/* ----------------------------------------------------- */

1233
	config_set_default_string(basicConfig, "Output", "Mode", "Simple");
J
jp9000 已提交
1234

1235
	config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
J
jp9000 已提交
1236
				  GetDefaultVideoSavePath().c_str());
1237
	config_set_default_string(basicConfig, "SimpleOutput", "RecFormat",
1238
				  "mkv");
J
jp9000 已提交
1239 1240 1241 1242 1243 1244
	config_set_default_uint(basicConfig, "SimpleOutput", "VBitrate", 2500);
	config_set_default_uint(basicConfig, "SimpleOutput", "ABitrate", 160);
	config_set_default_bool(basicConfig, "SimpleOutput", "UseAdvanced",
				false);
	config_set_default_bool(basicConfig, "SimpleOutput", "EnforceBitrate",
				true);
J
jp9000 已提交
1245
	config_set_default_string(basicConfig, "SimpleOutput", "Preset",
J
jp9000 已提交
1246
				  "veryfast");
1247
	config_set_default_string(basicConfig, "SimpleOutput", "NVENCPreset",
J
jp9000 已提交
1248
				  "hq");
1249
	config_set_default_string(basicConfig, "SimpleOutput", "RecQuality",
J
jp9000 已提交
1250
				  "Stream");
1251 1252 1253
	config_set_default_bool(basicConfig, "SimpleOutput", "RecRB", false);
	config_set_default_int(basicConfig, "SimpleOutput", "RecRBTime", 20);
	config_set_default_int(basicConfig, "SimpleOutput", "RecRBSize", 512);
1254
	config_set_default_string(basicConfig, "SimpleOutput", "RecRBPrefix",
J
jp9000 已提交
1255
				  "Replay");
1256

J
jp9000 已提交
1257 1258 1259 1260
	config_set_default_bool(basicConfig, "AdvOut", "ApplyServiceSettings",
				true);
	config_set_default_bool(basicConfig, "AdvOut", "UseRescale", false);
	config_set_default_uint(basicConfig, "AdvOut", "TrackIndex", 1);
J
jp9000 已提交
1261 1262 1263 1264 1265
	config_set_default_string(basicConfig, "AdvOut", "Encoder", "obs_x264");

	config_set_default_string(basicConfig, "AdvOut", "RecType", "Standard");

	config_set_default_string(basicConfig, "AdvOut", "RecFilePath",
J
jp9000 已提交
1266
				  GetDefaultVideoSavePath().c_str());
1267
	config_set_default_string(basicConfig, "AdvOut", "RecFormat", "mkv");
J
jp9000 已提交
1268 1269 1270
	config_set_default_bool(basicConfig, "AdvOut", "RecUseRescale", false);
	config_set_default_uint(basicConfig, "AdvOut", "RecTracks", (1 << 0));
	config_set_default_string(basicConfig, "AdvOut", "RecEncoder", "none");
1271
	config_set_default_uint(basicConfig, "AdvOut", "FLVTrack", 1);
J
jp9000 已提交
1272 1273

	config_set_default_bool(basicConfig, "AdvOut", "FFOutputToFile", true);
1274
	config_set_default_string(basicConfig, "AdvOut", "FFFilePath",
J
jp9000 已提交
1275
				  GetDefaultVideoSavePath().c_str());
1276
	config_set_default_string(basicConfig, "AdvOut", "FFExtension", "mp4");
J
jp9000 已提交
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296
	config_set_default_uint(basicConfig, "AdvOut", "FFVBitrate", 2500);
	config_set_default_uint(basicConfig, "AdvOut", "FFVGOPSize", 250);
	config_set_default_bool(basicConfig, "AdvOut", "FFUseRescale", false);
	config_set_default_bool(basicConfig, "AdvOut", "FFIgnoreCompat", false);
	config_set_default_uint(basicConfig, "AdvOut", "FFABitrate", 160);
	config_set_default_uint(basicConfig, "AdvOut", "FFAudioMixes", 1);

	config_set_default_uint(basicConfig, "AdvOut", "Track1Bitrate", 160);
	config_set_default_uint(basicConfig, "AdvOut", "Track2Bitrate", 160);
	config_set_default_uint(basicConfig, "AdvOut", "Track3Bitrate", 160);
	config_set_default_uint(basicConfig, "AdvOut", "Track4Bitrate", 160);
	config_set_default_uint(basicConfig, "AdvOut", "Track5Bitrate", 160);
	config_set_default_uint(basicConfig, "AdvOut", "Track6Bitrate", 160);

	config_set_default_bool(basicConfig, "AdvOut", "RecRB", false);
	config_set_default_uint(basicConfig, "AdvOut", "RecRBTime", 20);
	config_set_default_int(basicConfig, "AdvOut", "RecRBSize", 512);

	config_set_default_uint(basicConfig, "Video", "BaseCX", cx);
	config_set_default_uint(basicConfig, "Video", "BaseCY", cy);
1297

1298 1299 1300 1301 1302 1303 1304 1305
	/* don't allow BaseCX/BaseCY to be susceptible to defaults changing */
	if (!config_has_user_value(basicConfig, "Video", "BaseCX") ||
	    !config_has_user_value(basicConfig, "Video", "BaseCY")) {
		config_set_uint(basicConfig, "Video", "BaseCX", cx);
		config_set_uint(basicConfig, "Video", "BaseCY", cy);
		config_save_safe(basicConfig, "tmp", nullptr);
	}

1306
	config_set_default_string(basicConfig, "Output", "FilenameFormatting",
J
jp9000 已提交
1307
				  "%CCYY-%MM-%DD %hh-%mm-%ss");
1308

J
jp9000 已提交
1309 1310 1311
	config_set_default_bool(basicConfig, "Output", "DelayEnable", false);
	config_set_default_uint(basicConfig, "Output", "DelaySec", 20);
	config_set_default_bool(basicConfig, "Output", "DelayPreserve", true);
1312

J
jp9000 已提交
1313 1314 1315
	config_set_default_bool(basicConfig, "Output", "Reconnect", true);
	config_set_default_uint(basicConfig, "Output", "RetryDelay", 10);
	config_set_default_uint(basicConfig, "Output", "MaxRetries", 20);
1316

1317
	config_set_default_string(basicConfig, "Output", "BindIP", "default");
J
jp9000 已提交
1318 1319 1320 1321
	config_set_default_bool(basicConfig, "Output", "NewSocketLoopEnable",
				false);
	config_set_default_bool(basicConfig, "Output", "LowLatencyEnable",
				false);
1322

1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334
	int i = 0;
	uint32_t scale_cx = cx;
	uint32_t scale_cy = cy;

	/* use a default scaled resolution that has a pixel count no higher
	 * than 1280x720 */
	while (((scale_cx * scale_cy) > (1280 * 720)) && scaled_vals[i] > 0.0) {
		double scale = scaled_vals[i++];
		scale_cx = uint32_t(double(cx) / scale);
		scale_cy = uint32_t(double(cy) / scale);
	}

J
jp9000 已提交
1335 1336
	config_set_default_uint(basicConfig, "Video", "OutputCX", scale_cx);
	config_set_default_uint(basicConfig, "Video", "OutputCY", scale_cy);
1337

1338 1339 1340 1341 1342 1343 1344 1345 1346
	/* don't allow OutputCX/OutputCY to be susceptible to defaults
	 * changing */
	if (!config_has_user_value(basicConfig, "Video", "OutputCX") ||
	    !config_has_user_value(basicConfig, "Video", "OutputCY")) {
		config_set_uint(basicConfig, "Video", "OutputCX", scale_cx);
		config_set_uint(basicConfig, "Video", "OutputCY", scale_cy);
		config_save_safe(basicConfig, "tmp", nullptr);
	}

J
jp9000 已提交
1347
	config_set_default_uint(basicConfig, "Video", "FPSType", 0);
1348
	config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
J
jp9000 已提交
1349 1350 1351
	config_set_default_uint(basicConfig, "Video", "FPSInt", 30);
	config_set_default_uint(basicConfig, "Video", "FPSNum", 30);
	config_set_default_uint(basicConfig, "Video", "FPSDen", 1);
1352
	config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
1353
	config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
1354
	config_set_default_string(basicConfig, "Video", "ColorSpace", "601");
1355
	config_set_default_string(basicConfig, "Video", "ColorRange",
J
jp9000 已提交
1356
				  "Partial");
1357

1358
	config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
J
jp9000 已提交
1359 1360 1361 1362 1363 1364
				  "default");
	config_set_default_string(
		basicConfig, "Audio", "MonitoringDeviceName",
		Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
		    ".Default"));
	config_set_default_uint(basicConfig, "Audio", "SampleRate", 44100);
1365
	config_set_default_string(basicConfig, "Audio", "ChannelSetup",
J
jp9000 已提交
1366
				  "Stereo");
S
Shaolin 已提交
1367
	config_set_default_double(basicConfig, "Audio", "MeterDecayRate",
J
jp9000 已提交
1368 1369
				  VOLUME_METER_DECAY_FAST);
	config_set_default_uint(basicConfig, "Audio", "PeakMeterType", 0);
1370

1371 1372
	CheckExistingCookieId();

1373 1374 1375
	return true;
}

1376 1377 1378 1379
extern bool EncoderAvailable(const char *encoder);

void OBSBasic::InitBasicConfigDefaults2()
{
J
jp9000 已提交
1380 1381
	bool oldEncDefaults = config_get_bool(App()->GlobalConfig(), "General",
					      "Pre23Defaults");
1382 1383 1384
	bool useNV = EncoderAvailable("ffmpeg_nvenc") && !oldEncDefaults;

	config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
J
jp9000 已提交
1385 1386
				  useNV ? SIMPLE_ENCODER_NVENC
					: SIMPLE_ENCODER_X264);
1387
	config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
J
jp9000 已提交
1388 1389
				  useNV ? SIMPLE_ENCODER_NVENC
					: SIMPLE_ENCODER_X264);
1390 1391
}

1392 1393
bool OBSBasic::InitBasicConfig()
{
P
Palana 已提交
1394 1395
	ProfileScope("OBSBasic::InitBasicConfig");

1396
	char configPath[512];
J
jp9000 已提交
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409

	int ret = GetProfilePath(configPath, sizeof(configPath), "");
	if (ret <= 0) {
		OBSErrorBox(nullptr, "Failed to get profile path");
		return false;
	}

	if (os_mkdir(configPath) == MKDIR_ERROR) {
		OBSErrorBox(nullptr, "Failed to create profile path");
		return false;
	}

	ret = GetProfilePath(configPath, sizeof(configPath), "basic.ini");
1410 1411 1412 1413
	if (ret <= 0) {
		OBSErrorBox(nullptr, "Failed to get base.ini path");
		return false;
	}
1414

1415 1416 1417
	int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
	if (code != CONFIG_SUCCESS) {
		OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
1418 1419 1420
		return false;
	}

J
jp9000 已提交
1421 1422
	if (config_get_string(basicConfig, "General", "Name") == nullptr) {
		const char *curName = config_get_string(App()->GlobalConfig(),
J
jp9000 已提交
1423
							"Basic", "Profile");
J
jp9000 已提交
1424 1425

		config_set_string(basicConfig, "General", "Name", curName);
1426
		basicConfig.SaveSafe("tmp");
J
jp9000 已提交
1427 1428
	}

1429 1430 1431
	return InitBasicConfigDefaults();
}

1432 1433
void OBSBasic::InitOBSCallbacks()
{
P
Palana 已提交
1434 1435
	ProfileScope("OBSBasic::InitOBSCallbacks");

1436
	signalHandlers.reserve(signalHandlers.size() + 7);
1437
	signalHandlers.emplace_back(obs_get_signal_handler(), "source_create",
J
jp9000 已提交
1438
				    OBSBasic::SourceCreated, this);
P
Palana 已提交
1439
	signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
J
jp9000 已提交
1440
				    OBSBasic::SourceRemoved, this);
P
Palana 已提交
1441
	signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
J
jp9000 已提交
1442 1443 1444 1445
				    OBSBasic::SourceActivated, this);
	signalHandlers.emplace_back(obs_get_signal_handler(),
				    "source_deactivate",
				    OBSBasic::SourceDeactivated, this);
1446 1447 1448 1449 1450 1451
	signalHandlers.emplace_back(obs_get_signal_handler(),
				    "source_audio_activate",
				    OBSBasic::SourceAudioActivated, this);
	signalHandlers.emplace_back(obs_get_signal_handler(),
				    "source_audio_deactivate",
				    OBSBasic::SourceAudioDeactivated, this);
P
Palana 已提交
1452
	signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
J
jp9000 已提交
1453
				    OBSBasic::SourceRenamed, this);
1454 1455
}

J
jp9000 已提交
1456 1457
void OBSBasic::InitPrimitives()
{
P
Palana 已提交
1458 1459
	ProfileScope("OBSBasic::InitPrimitives");

J
jp9000 已提交
1460
	obs_enter_graphics();
J
jp9000 已提交
1461

1462
	gs_render_start(true);
J
jp9000 已提交
1463 1464 1465
	gs_vertex2f(0.0f, 0.0f);
	gs_vertex2f(0.0f, 1.0f);
	gs_vertex2f(1.0f, 0.0f);
1466
	gs_vertex2f(1.0f, 1.0f);
1467
	box = gs_render_save();
J
jp9000 已提交
1468

1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
	gs_render_start(true);
	gs_vertex2f(0.0f, 0.0f);
	gs_vertex2f(0.0f, 1.0f);
	boxLeft = gs_render_save();

	gs_render_start(true);
	gs_vertex2f(0.0f, 0.0f);
	gs_vertex2f(1.0f, 0.0f);
	boxTop = gs_render_save();

	gs_render_start(true);
	gs_vertex2f(1.0f, 0.0f);
	gs_vertex2f(1.0f, 1.0f);
	boxRight = gs_render_save();

	gs_render_start(true);
	gs_vertex2f(0.0f, 1.0f);
	gs_vertex2f(1.0f, 1.0f);
	boxBottom = gs_render_save();

1489
	gs_render_start(true);
J
jp9000 已提交
1490
	for (int i = 0; i <= 360; i += (360 / 20)) {
J
jp9000 已提交
1491 1492 1493
		float pos = RAD(float(i));
		gs_vertex2f(cosf(pos), sinf(pos));
	}
1494
	circle = gs_render_save();
J
jp9000 已提交
1495

J
jp9000 已提交
1496
	obs_leave_graphics();
J
jp9000 已提交
1497 1498
}

J
jp9000 已提交
1499 1500 1501 1502 1503 1504 1505 1506
void OBSBasic::ReplayBufferClicked()
{
	if (outputHandler->ReplayBufferActive())
		StopReplayBuffer();
	else
		StartReplayBuffer();
};

J
jp9000 已提交
1507 1508
void OBSBasic::ResetOutputs()
{
P
Palana 已提交
1509 1510
	ProfileScope("OBSBasic::ResetOutputs");

J
jp9000 已提交
1511 1512 1513
	const char *mode = config_get_string(basicConfig, "Output", "Mode");
	bool advOut = astrcmpi(mode, "Advanced") == 0;

J
jp9000 已提交
1514 1515
	if (!outputHandler || !outputHandler->Active()) {
		outputHandler.reset();
J
jp9000 已提交
1516 1517
		outputHandler.reset(advOut ? CreateAdvancedOutputHandler(this)
					   : CreateSimpleOutputHandler(this));
1518

J
jp9000 已提交
1519
		delete replayBufferButton;
1520
		delete replayLayout;
J
jp9000 已提交
1521 1522

		if (outputHandler->replayBuffer) {
1523
			replayBufferButton = new ReplayBufferButton(
J
jp9000 已提交
1524
				QTStr("Basic.Main.StartReplayBuffer"), this);
1525
			replayBufferButton->setCheckable(true);
1526
			connect(replayBufferButton.data(),
1527
				&QPushButton::clicked, this,
J
jp9000 已提交
1528
				&OBSBasic::ReplayBufferClicked);
J
jp9000 已提交
1529

1530 1531 1532
			replayLayout = new QHBoxLayout(this);
			replayLayout->addWidget(replayBufferButton);

J
jp9000 已提交
1533 1534
			replayBufferButton->setProperty("themeID",
							"replayBufferButton");
1535
			ui->buttonsVLayout->insertLayout(2, replayLayout);
J
jp9000 已提交
1536
		}
1537

J
jp9000 已提交
1538 1539
		if (sysTrayReplayBuffer)
			sysTrayReplayBuffer->setEnabled(
J
jp9000 已提交
1540
				!!outputHandler->replayBuffer);
J
jp9000 已提交
1541 1542 1543 1544 1545
	} else {
		outputHandler->Update();
	}
}

J
jp9000 已提交
1546
static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
J
jp9000 已提交
1547
				     const char *slot);
J
jp9000 已提交
1548

1549 1550 1551 1552
#define STARTUP_SEPARATOR \
	"==== Startup complete ==============================================="
#define SHUTDOWN_SEPARATOR \
	"==== Shutting down =================================================="
1553

J
jp9000 已提交
1554
#define UNSUPPORTED_ERROR                                                     \
1555 1556 1557
	"Failed to initialize video:\n\nRequired graphics API functionality " \
	"not found.  Your GPU may not be supported."

J
jp9000 已提交
1558
#define UNKNOWN_ERROR                                                  \
1559 1560
	"Failed to initialize video.  Your GPU may not be supported, " \
	"or your graphics drivers may need to be updated."
1561

1562 1563
void OBSBasic::OBSInit()
{
P
Palana 已提交
1564 1565
	ProfileScope("OBSBasic::OBSInit");

J
jp9000 已提交
1566 1567
	const char *sceneCollection = config_get_string(
		App()->GlobalConfig(), "Basic", "SceneCollectionFile");
1568
	char savePath[512];
J
jp9000 已提交
1569 1570 1571 1572 1573 1574 1575
	char fileName[512];
	int ret;

	if (!sceneCollection)
		throw "Failed to get scene collection name";

	ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
J
jp9000 已提交
1576
		       sceneCollection);
1577
	if (ret <= 0)
J
jp9000 已提交
1578 1579 1580 1581 1582
		throw "Failed to create scene collection file name";

	ret = GetConfigPath(savePath, sizeof(savePath), fileName);
	if (ret <= 0)
		throw "Failed to get scene collection json file path";
1583

1584 1585
	if (!InitBasicConfig())
		throw "Failed to load basic.ini";
1586
	if (!ResetAudio())
1587 1588
		throw "Failed to initialize audio";

1589
	ret = ResetVideo();
1590 1591 1592 1593 1594

	switch (ret) {
	case OBS_VIDEO_MODULE_NOT_FOUND:
		throw "Failed to initialize video:  Graphics module not found";
	case OBS_VIDEO_NOT_SUPPORTED:
1595
		throw UNSUPPORTED_ERROR;
1596 1597 1598 1599
	case OBS_VIDEO_INVALID_PARAM:
		throw "Failed to initialize video:  Invalid parameters";
	default:
		if (ret != OBS_VIDEO_SUCCESS)
1600
			throw UNKNOWN_ERROR;
1601 1602
	}

1603
	/* load audio monitoring */
1604
#if defined(_WIN32) || defined(__APPLE__) || HAVE_PULSEAUDIO
J
jp9000 已提交
1605 1606 1607 1608
	const char *device_name =
		config_get_string(basicConfig, "Audio", "MonitoringDeviceName");
	const char *device_id =
		config_get_string(basicConfig, "Audio", "MonitoringDeviceId");
1609 1610

	obs_set_audio_monitoring_device(device_name, device_id);
1611 1612

	blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s",
J
jp9000 已提交
1613
	     device_name, device_id);
1614 1615
#endif

1616
	InitOBSCallbacks();
P
Palana 已提交
1617
	InitHotkeys();
1618

1619
	AddExtraModulePaths();
1620
	blog(LOG_INFO, "---------------------------------");
J
jp9000 已提交
1621
	obs_load_all_modules();
1622 1623
	blog(LOG_INFO, "---------------------------------");
	obs_log_loaded_modules();
1624 1625
	blog(LOG_INFO, "---------------------------------");
	obs_post_load_modules();
J
jp9000 已提交
1626

1627
#ifdef BROWSER_AVAILABLE
J
jp9000 已提交
1628
	cef = obs_browser_init_panel();
J
jp9000 已提交
1629 1630
#endif

1631 1632
	InitBasicConfigDefaults2();

1633 1634
	CheckForSimpleModeX264Fallback();

1635
	blog(LOG_INFO, STARTUP_SEPARATOR);
1636

J
jp9000 已提交
1637
	ResetOutputs();
1638
	CreateHotkeys();
J
jp9000 已提交
1639

1640 1641 1642
	if (!InitService())
		throw "Failed to initialize service";

J
jp9000 已提交
1643 1644
	InitPrimitives();

J
jp9000 已提交
1645 1646 1647 1648 1649 1650
	sceneDuplicationMode = config_get_bool(
		App()->GlobalConfig(), "BasicWindow", "SceneDuplicationMode");
	swapScenesMode = config_get_bool(App()->GlobalConfig(), "BasicWindow",
					 "SwapScenesMode");
	editPropertiesMode = config_get_bool(
		App()->GlobalConfig(), "BasicWindow", "EditPropertiesMode");
C
cg2121 已提交
1651

J
jp9000 已提交
1652 1653 1654 1655
#define SET_VISIBILITY(name, control)                                         \
	do {                                                                  \
		if (config_has_user_value(App()->GlobalConfig(),              \
					  "BasicWindow", name)) {             \
1656
			bool visible = config_get_bool(App()->GlobalConfig(), \
J
jp9000 已提交
1657 1658 1659
						       "BasicWindow", name);  \
			ui->control->setChecked(visible);                     \
		}                                                             \
1660 1661 1662 1663 1664 1665
	} while (false)

	SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars);
	SET_VISIBILITY("ShowStatusBar", toggleStatusBar);
#undef SET_VISIBILITY

1666 1667 1668 1669
	bool sourceIconsVisible = config_get_bool(
		GetGlobalConfig(), "BasicWindow", "ShowSourceIcons");
	ui->toggleSourceIcons->setChecked(sourceIconsVisible);

1670 1671 1672 1673 1674 1675 1676
	{
		ProfileScope("OBSBasic::Load");
		disableSaving--;
		Load(savePath);
		disableSaving++;
	}

J
jp9000 已提交
1677
	TimedCheckForUpdates();
1678
	loaded = true;
J
jp9000 已提交
1679

J
jp9000 已提交
1680 1681
	previewEnabled = config_get_bool(App()->GlobalConfig(), "BasicWindow",
					 "PreviewEnabled");
1682 1683 1684

	if (!previewEnabled && !IsPreviewProgramMode())
		QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
J
jp9000 已提交
1685 1686
					  Qt::QueuedConnection,
					  Q_ARG(bool, previewEnabled));
1687 1688 1689 1690

#ifdef _WIN32
	uint32_t winVer = GetWindowsVersion();
	if (winVer > 0 && winVer < 0x602) {
J
jp9000 已提交
1691 1692
		bool disableAero =
			config_get_bool(basicConfig, "Video", "DisableAero");
1693 1694 1695
		SetAeroEnabled(!disableAero);
	}
#endif
J
jp9000 已提交
1696

1697
	RefreshSceneCollections();
J
jp9000 已提交
1698
	RefreshProfiles();
J
jp9000 已提交
1699
	disableSaving--;
1700

J
jp9000 已提交
1701
	auto addDisplay = [this](OBSQTDisplay *window) {
1702
		obs_display_add_draw_callback(window->GetDisplay(),
J
jp9000 已提交
1703
					      OBSBasic::RenderMain, this);
1704 1705 1706 1707 1708 1709 1710 1711

		struct obs_video_info ovi;
		if (obs_get_video_info(&ovi))
			ResizePreview(ovi.base_width, ovi.base_height);
	};

	connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDisplay);

1712
#ifdef _WIN32
J
jp9000 已提交
1713
	SetWin32DropStyle(this);
1714 1715 1716 1717
	show();
#endif

	bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
J
jp9000 已提交
1718
					   "AlwaysOnTop");
1719
	if (alwaysOnTop || opt_always_on_top) {
1720 1721 1722 1723 1724
		SetAlwaysOnTop(this, true);
		ui->actionAlwaysOnTop->setChecked(true);
	}

#ifndef _WIN32
1725
	show();
1726
#endif
J
jp9000 已提交
1727

A
Alex Anderson 已提交
1728
	/* setup stats dock */
1729 1730
	OBSBasicStats *statsDlg = new OBSBasicStats(statsDock, false);
	statsDock->setWidget(statsDlg);
A
Alex Anderson 已提交
1731

1732 1733 1734 1735 1736 1737 1738
	/* ----------------------------- */
	/* add custom browser docks      */

#ifdef BROWSER_AVAILABLE
	if (cef) {
		QAction *action = new QAction(QTStr("Basic.MainMenu."
						    "View.Docks."
1739 1740
						    "CustomBrowserDocks"),
					      this);
1741 1742 1743 1744 1745 1746 1747 1748 1749
		ui->viewMenuDocks->insertAction(ui->toggleScenes, action);
		connect(action, &QAction::triggered, this,
			&OBSBasic::ManageExtraBrowserDocks);
		ui->viewMenuDocks->insertSeparator(ui->toggleScenes);

		LoadExtraBrowserDocks();
	}
#endif

J
jp9000 已提交
1750 1751
	const char *dockStateStr = config_get_string(
		App()->GlobalConfig(), "BasicWindow", "DockState");
J
jp9000 已提交
1752 1753
	if (!dockStateStr) {
		on_resetUI_triggered();
J
jp9000 已提交
1754
	} else {
J
jp9000 已提交
1755 1756 1757 1758
		QByteArray dockState =
			QByteArray::fromBase64(QByteArray(dockStateStr));
		if (!restoreState(dockState))
			on_resetUI_triggered();
J
jp9000 已提交
1759 1760
	}

J
jp9000 已提交
1761 1762
	bool pre23Defaults = config_get_bool(App()->GlobalConfig(), "General",
					     "Pre23Defaults");
1763
	if (pre23Defaults) {
J
jp9000 已提交
1764 1765
		bool resetDockLock23 = config_get_bool(
			App()->GlobalConfig(), "General", "ResetDockLock23");
1766
		if (!resetDockLock23) {
J
jp9000 已提交
1767 1768
			config_set_bool(App()->GlobalConfig(), "General",
					"ResetDockLock23", true);
1769
			config_remove_value(App()->GlobalConfig(),
J
jp9000 已提交
1770
					    "BasicWindow", "DocksLocked");
1771 1772 1773
			config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
		}
	}
J
jp9000 已提交
1774

J
jp9000 已提交
1775 1776
	bool docksLocked = config_get_bool(App()->GlobalConfig(), "BasicWindow",
					   "DocksLocked");
J
jp9000 已提交
1777 1778 1779 1780
	on_lockUI_toggled(docksLocked);
	ui->lockUI->blockSignals(true);
	ui->lockUI->setChecked(docksLocked);
	ui->lockUI->blockSignals(false);
C
cg2121 已提交
1781

1782
#ifndef __APPLE__
C
cg2121 已提交
1783
	SystemTray(true);
1784
#endif
C
cg2121 已提交
1785

1786 1787 1788 1789 1790
#ifdef _WIN32
	taskBtn->setWindow(windowHandle());
	taskProg->setRange(0, 1);
#endif

J
jp9000 已提交
1791
	bool has_last_version = config_has_user_value(App()->GlobalConfig(),
J
jp9000 已提交
1792 1793 1794
						      "General", "LastVersion");
	bool first_run =
		config_get_bool(App()->GlobalConfig(), "General", "FirstRun");
J
jp9000 已提交
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805

	if (!first_run) {
		config_set_bool(App()->GlobalConfig(), "General", "FirstRun",
				true);
		config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
	}

	if (!first_run && !has_last_version && !Active()) {
		QString msg;
		msg = QTStr("Basic.FirstStartup.RunWizard");

J
jp9000 已提交
1806 1807
		QMessageBox::StandardButton button = OBSMessageBox::question(
			this, QTStr("Basic.AutoConfig"), msg);
J
jp9000 已提交
1808 1809

		if (button == QMessageBox::Yes) {
J
jp9000 已提交
1810
			QMetaObject::invokeMethod(this,
J
jp9000 已提交
1811 1812
						  "on_autoConfigure_triggered",
						  Qt::QueuedConnection);
J
jp9000 已提交
1813 1814
		} else {
			msg = QTStr("Basic.FirstStartup.RunWizard.NoClicked");
J
jp9000 已提交
1815 1816
			OBSMessageBox::information(
				this, QTStr("Basic.AutoConfig"), msg);
J
jp9000 已提交
1817 1818
		}
	}
1819

1820
	ToggleMixerLayout(config_get_bool(App()->GlobalConfig(), "BasicWindow",
J
jp9000 已提交
1821
					  "VerticalVolControl"));
S
Shaolin 已提交
1822

1823 1824
	if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
		on_stats_triggered();
1825 1826

	OBSBasicStats::InitializeValues();
J
jp9000 已提交
1827 1828 1829 1830 1831 1832

	/* ----------------------- */
	/* Add multiview menu      */

	ui->viewMenu->addSeparator();

1833
	multiviewProjectorMenu = new QMenu(QTStr("MultiviewProjector"));
J
jp9000 已提交
1834
	ui->viewMenu->addMenu(multiviewProjectorMenu);
1835
	AddProjectorMenuMonitors(multiviewProjectorMenu, this,
J
jp9000 已提交
1836
				 SLOT(OpenMultiviewProjector()));
1837 1838
	connect(ui->viewMenu->menuAction(), &QAction::hovered, this,
		&OBSBasic::UpdateMultiviewProjectorMenu);
J
jp9000 已提交
1839 1840
	ui->viewMenu->addAction(QTStr("MultiviewWindowed"), this,
				SLOT(OpenMultiviewWindow()));
C
cg2121 已提交
1841

C
Clayton Groeneveld 已提交
1842 1843
	ui->sources->UpdateIcons();

1844 1845 1846 1847 1848 1849 1850 1851 1852
	if (!opt_studio_mode) {
		SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
						      "BasicWindow",
						      "PreviewProgramMode"));
	} else {
		SetPreviewProgramMode(true);
		opt_studio_mode = false;
	}

C
cg2121 已提交
1853
#if !defined(_WIN32) && !defined(__APPLE__)
J
jp9000 已提交
1854 1855 1856
	delete ui->actionShowCrashLogs;
	delete ui->actionUploadLastCrashLog;
	delete ui->menuCrashLogs;
C
cg2121 已提交
1857
	delete ui->actionCheckForUpdates;
J
jp9000 已提交
1858 1859 1860
	ui->actionShowCrashLogs = nullptr;
	ui->actionUploadLastCrashLog = nullptr;
	ui->menuCrashLogs = nullptr;
C
cg2121 已提交
1861 1862
	ui->actionCheckForUpdates = nullptr;
#endif
1863

1864 1865
	OnFirstLoad();

1866
#ifdef __APPLE__
1867
	QMetaObject::invokeMethod(this, "DeferredSysTrayLoad",
J
jp9000 已提交
1868
				  Qt::QueuedConnection, Q_ARG(int, 10));
1869
#endif
1870 1871
}

1872 1873 1874 1875
void OBSBasic::OnFirstLoad()
{
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_FINISHED_LOADING);
J
jp9000 已提交
1876

1877
#if defined(BROWSER_AVAILABLE) && defined(_WIN32)
J
jp9000 已提交
1878
	/* Attempt to load init screen if available */
J
jp9000 已提交
1879
	if (cef) {
J
jp9000 已提交
1880 1881
		WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
		if (wnit) {
J
jp9000 已提交
1882 1883
			connect(wnit, &WhatsNewInfoThread::Result, this,
				&OBSBasic::ReceivedIntroJson);
J
jp9000 已提交
1884 1885
		}
		if (wnit) {
1886
			introCheckThread.reset(wnit);
J
jp9000 已提交
1887 1888 1889 1890
			introCheckThread->start();
		}
	}
#endif
J
jp9000 已提交
1891 1892

	Auth::Load();
1893 1894
}

1895
void OBSBasic::DeferredSysTrayLoad(int requeueCount)
1896 1897
{
	if (--requeueCount > 0) {
1898
		QMetaObject::invokeMethod(this, "DeferredSysTrayLoad",
J
jp9000 已提交
1899 1900
					  Qt::QueuedConnection,
					  Q_ARG(int, requeueCount));
1901 1902 1903
		return;
	}

1904 1905 1906
	/* Minimizng to tray on initial startup does not work on mac
	 * unless it is done in the deferred load */
	SystemTray(true);
1907 1908
}

J
jp9000 已提交
1909 1910 1911
/* shows a "what's new" page on startup of new versions using CEF */
void OBSBasic::ReceivedIntroJson(const QString &text)
{
1912
#ifdef BROWSER_AVAILABLE
J
jp9000 已提交
1913
#ifdef _WIN32
1914 1915 1916
	if (closing)
		return;

J
jp9000 已提交
1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
	std::string err;
	Json json = Json::parse(QT_TO_UTF8(text), err);
	if (!err.empty())
		return;

	std::string info_url;
	int info_increment = -1;

	/* check to see if there's an info page for this version */
	const Json::array &items = json.array_items();
	for (const Json &item : items) {
		const std::string &version = item["version"].string_value();
		const std::string &url = item["url"].string_value();
		int increment = item["increment"].int_value();
1931
		int rc = item["RC"].int_value();
J
jp9000 已提交
1932 1933 1934 1935 1936

		int major = 0;
		int minor = 0;

		sscanf(version.c_str(), "%d.%d", &major, &minor);
1937 1938 1939 1940 1941
#if OBS_RELEASE_CANDIDATE > 0
		if (major == OBS_RELEASE_CANDIDATE_MAJOR &&
		    minor == OBS_RELEASE_CANDIDATE_MINOR &&
		    rc == OBS_RELEASE_CANDIDATE) {
#else
J
jp9000 已提交
1942
		if (major == LIBOBS_API_MAJOR_VER &&
J
jp9000 已提交
1943
		    minor == LIBOBS_API_MINOR_VER && rc == 0) {
1944
#endif
J
jp9000 已提交
1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
			info_url = url;
			info_increment = increment;
		}
	}

	/* this version was not found, or no info for this version */
	if (info_increment == -1) {
		return;
	}

1955 1956
#if OBS_RELEASE_CANDIDATE > 0
	uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
J
jp9000 已提交
1957
					      "LastRCVersion");
1958
#else
J
jp9000 已提交
1959 1960
	uint32_t lastVersion =
		config_get_int(App()->GlobalConfig(), "General", "LastVersion");
1961
#endif
J
jp9000 已提交
1962 1963 1964

	int current_version_increment = -1;

1965 1966 1967
#if OBS_RELEASE_CANDIDATE > 0
	if (lastVersion < OBS_RELEASE_CANDIDATE_VER) {
#else
1968
	if ((lastVersion & ~0xFFFF) < (LIBOBS_API_VER & ~0xFFFF)) {
1969
#endif
J
jp9000 已提交
1970
		config_set_int(App()->GlobalConfig(), "General",
J
jp9000 已提交
1971
			       "InfoIncrement", -1);
J
jp9000 已提交
1972 1973
	} else {
		current_version_increment = config_get_int(
J
jp9000 已提交
1974
			App()->GlobalConfig(), "General", "InfoIncrement");
J
jp9000 已提交
1975 1976 1977 1978 1979 1980
	}

	if (info_increment <= current_version_increment) {
		return;
	}

J
jp9000 已提交
1981 1982
	config_set_int(App()->GlobalConfig(), "General", "InfoIncrement",
		       info_increment);
J
jp9000 已提交
1983

1984 1985 1986 1987 1988 1989 1990
	/* Don't show What's New dialog for new users */
#if !defined(OBS_RELEASE_CANDIDATE) || OBS_RELEASE_CANDIDATE == 0
	if (!lastVersion) {
		return;
	}
#endif
	cef->init_browser();
1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017

	WhatsNewBrowserInitThread *wnbit =
		new WhatsNewBrowserInitThread(QT_UTF8(info_url.c_str()));
	if (wnbit) {
		connect(wnbit, &WhatsNewBrowserInitThread::Result, this,
			&OBSBasic::ShowWhatsNew);
	}
	if (wnbit) {
		whatsNewInitThread.reset(wnbit);
		whatsNewInitThread->start();
	}
#else
	UNUSED_PARAMETER(text);
#endif
#else
	UNUSED_PARAMETER(text);
#endif
}

void OBSBasic::ShowWhatsNew(const QString &url)
{
#ifdef BROWSER_AVAILABLE
#ifdef _WIN32
	if (closing)
		return;

	std::string info_url = QT_TO_UTF8(url);
2018

J
jp9000 已提交
2019 2020 2021 2022
	QDialog *dlg = new QDialog(this);
	dlg->setAttribute(Qt::WA_DeleteOnClose, true);
	dlg->setWindowTitle("What's New");
	dlg->resize(700, 600);
J
jp9000 已提交
2023

2024 2025 2026 2027
	Qt::WindowFlags flags = dlg->windowFlags();
	Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint;
	dlg->setWindowFlags(flags & (~helpFlag));

J
jp9000 已提交
2028
	QCefWidget *cefWidget = cef->create_widget(nullptr, info_url);
J
jp9000 已提交
2029 2030 2031 2032
	if (!cefWidget) {
		return;
	}

J
jp9000 已提交
2033 2034
	connect(cefWidget, SIGNAL(titleChanged(const QString &)), dlg,
		SLOT(setWindowTitle(const QString &)));
J
jp9000 已提交
2035 2036

	QPushButton *close = new QPushButton(QTStr("Close"));
J
jp9000 已提交
2037
	connect(close, &QAbstractButton::clicked, dlg, &QDialog::accept);
J
jp9000 已提交
2038 2039 2040 2041 2042 2043

	QHBoxLayout *bottomLayout = new QHBoxLayout();
	bottomLayout->addStretch();
	bottomLayout->addWidget(close);
	bottomLayout->addStretch();

J
jp9000 已提交
2044
	QVBoxLayout *topLayout = new QVBoxLayout(dlg);
J
jp9000 已提交
2045 2046 2047
	topLayout->addWidget(cefWidget);
	topLayout->addLayout(bottomLayout);

J
jp9000 已提交
2048
	dlg->show();
J
jp9000 已提交
2049
#else
2050
	UNUSED_PARAMETER(url);
J
jp9000 已提交
2051
#endif
2052
#else
2053
	UNUSED_PARAMETER(url);
2054
#endif
J
jp9000 已提交
2055 2056
}

2057 2058 2059 2060 2061 2062 2063
void OBSBasic::UpdateMultiviewProjectorMenu()
{
	multiviewProjectorMenu->clear();
	AddProjectorMenuMonitors(multiviewProjectorMenu, this,
				 SLOT(OpenMultiviewProjector()));
}

P
Palana 已提交
2064 2065
void OBSBasic::InitHotkeys()
{
P
Palana 已提交
2066 2067
	ProfileScope("OBSBasic::InitHotkeys");

P
Palana 已提交
2068
	struct obs_hotkeys_translations t = {};
J
jp9000 已提交
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
	t.insert = Str("Hotkeys.Insert");
	t.del = Str("Hotkeys.Delete");
	t.home = Str("Hotkeys.Home");
	t.end = Str("Hotkeys.End");
	t.page_up = Str("Hotkeys.PageUp");
	t.page_down = Str("Hotkeys.PageDown");
	t.num_lock = Str("Hotkeys.NumLock");
	t.scroll_lock = Str("Hotkeys.ScrollLock");
	t.caps_lock = Str("Hotkeys.CapsLock");
	t.backspace = Str("Hotkeys.Backspace");
	t.tab = Str("Hotkeys.Tab");
	t.print = Str("Hotkeys.Print");
	t.pause = Str("Hotkeys.Pause");
	t.left = Str("Hotkeys.Left");
	t.right = Str("Hotkeys.Right");
	t.up = Str("Hotkeys.Up");
	t.down = Str("Hotkeys.Down");
P
Palana 已提交
2086
#ifdef _WIN32
J
jp9000 已提交
2087
	t.meta = Str("Hotkeys.Windows");
P
Palana 已提交
2088
#else
J
jp9000 已提交
2089
	t.meta = Str("Hotkeys.Super");
P
Palana 已提交
2090
#endif
J
jp9000 已提交
2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107
	t.menu = Str("Hotkeys.Menu");
	t.space = Str("Hotkeys.Space");
	t.numpad_num = Str("Hotkeys.NumpadNum");
	t.numpad_multiply = Str("Hotkeys.NumpadMultiply");
	t.numpad_divide = Str("Hotkeys.NumpadDivide");
	t.numpad_plus = Str("Hotkeys.NumpadAdd");
	t.numpad_minus = Str("Hotkeys.NumpadSubtract");
	t.numpad_decimal = Str("Hotkeys.NumpadDecimal");
	t.apple_keypad_num = Str("Hotkeys.AppleKeypadNum");
	t.apple_keypad_multiply = Str("Hotkeys.AppleKeypadMultiply");
	t.apple_keypad_divide = Str("Hotkeys.AppleKeypadDivide");
	t.apple_keypad_plus = Str("Hotkeys.AppleKeypadAdd");
	t.apple_keypad_minus = Str("Hotkeys.AppleKeypadSubtract");
	t.apple_keypad_decimal = Str("Hotkeys.AppleKeypadDecimal");
	t.apple_keypad_equal = Str("Hotkeys.AppleKeypadEqual");
	t.mouse_num = Str("Hotkeys.MouseButton");
	t.escape = Str("Hotkeys.Escape");
P
Palana 已提交
2108 2109 2110
	obs_hotkeys_set_translations(&t);

	obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
J
jp9000 已提交
2111 2112
						   Str("Push-to-mute"),
						   Str("Push-to-talk"));
P
Palana 已提交
2113

J
jp9000 已提交
2114 2115
	obs_hotkeys_set_sceneitem_hotkeys_translations(Str("SceneItemShow"),
						       Str("SceneItemHide"));
P
Palana 已提交
2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127

	obs_hotkey_enable_callback_rerouting(true);
	obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this);
}

void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed)
{
	obs_hotkey_trigger_routed_callback(id, pressed);
}

void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed)
{
J
jp9000 已提交
2128
	OBSBasic &basic = *static_cast<OBSBasic *>(data);
P
Palana 已提交
2129
	QMetaObject::invokeMethod(&basic, "ProcessHotkey",
J
jp9000 已提交
2130 2131
				  Q_ARG(obs_hotkey_id, id),
				  Q_ARG(bool, pressed));
P
Palana 已提交
2132 2133
}

2134 2135
void OBSBasic::CreateHotkeys()
{
P
Palana 已提交
2136 2137
	ProfileScope("OBSBasic::CreateHotkeys");

J
jp9000 已提交
2138 2139 2140
	auto LoadHotkeyData = [&](const char *name) -> OBSData {
		const char *info =
			config_get_string(basicConfig, "Hotkeys", name);
2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152
		if (!info)
			return {};

		obs_data_t *data = obs_data_create_from_json(info);
		if (!data)
			return {};

		OBSData res = data;
		obs_data_release(data);
		return res;
	};

J
jp9000 已提交
2153
	auto LoadHotkey = [&](obs_hotkey_id id, const char *name) {
J
jp9000 已提交
2154 2155 2156 2157 2158 2159 2160
		obs_data_array_t *array =
			obs_data_get_array(LoadHotkeyData(name), "bindings");

		obs_hotkey_load(id, array);
		obs_data_array_release(array);
	};

2161
	auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
J
jp9000 已提交
2162
				  const char *name1) {
2163 2164 2165 2166 2167 2168 2169 2170 2171 2172
		obs_data_array_t *array0 =
			obs_data_get_array(LoadHotkeyData(name0), "bindings");
		obs_data_array_t *array1 =
			obs_data_get_array(LoadHotkeyData(name1), "bindings");

		obs_hotkey_pair_load(id, array0, array1);
		obs_data_array_release(array0);
		obs_data_array_release(array1);
	};

J
jp9000 已提交
2173 2174 2175 2176 2177 2178 2179 2180 2181
#define MAKE_CALLBACK(pred, method, log_action)                            \
	[](void *data, obs_hotkey_pair_id, obs_hotkey_t *, bool pressed) { \
		OBSBasic &basic = *static_cast<OBSBasic *>(data);          \
		if ((pred) && pressed) {                                   \
			blog(LOG_INFO, log_action " due to hotkey");       \
			method();                                          \
			return true;                                       \
		}                                                          \
		return false;                                              \
2182 2183 2184
	}

	streamingHotkeys = obs_hotkey_pair_register_frontend(
J
jp9000 已提交
2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198
		"OBSBasic.StartStreaming", Str("Basic.Main.StartStreaming"),
		"OBSBasic.StopStreaming", Str("Basic.Main.StopStreaming"),
		MAKE_CALLBACK(!basic.outputHandler->StreamingActive() &&
				      basic.ui->streamButton->isEnabled(),
			      basic.StartStreaming, "Starting stream"),
		MAKE_CALLBACK(basic.outputHandler->StreamingActive() &&
				      basic.ui->streamButton->isEnabled(),
			      basic.StopStreaming, "Stopping stream"),
		this, this);
	LoadHotkeyPair(streamingHotkeys, "OBSBasic.StartStreaming",
		       "OBSBasic.StopStreaming");

	auto cb = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
		OBSBasic &basic = *static_cast<OBSBasic *>(data);
J
jp9000 已提交
2199 2200 2201 2202 2203 2204
		if (basic.outputHandler->StreamingActive() && pressed) {
			basic.ForceStopStreaming();
		}
	};

	forceStreamingStopHotkey = obs_hotkey_register_frontend(
J
jp9000 已提交
2205 2206 2207
		"OBSBasic.ForceStopStreaming",
		Str("Basic.Main.ForceStopStreaming"), cb, this);
	LoadHotkey(forceStreamingStopHotkey, "OBSBasic.ForceStopStreaming");
J
jp9000 已提交
2208

2209
	recordingHotkeys = obs_hotkey_pair_register_frontend(
J
jp9000 已提交
2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220
		"OBSBasic.StartRecording", Str("Basic.Main.StartRecording"),
		"OBSBasic.StopRecording", Str("Basic.Main.StopRecording"),
		MAKE_CALLBACK(!basic.outputHandler->RecordingActive() &&
				      !basic.ui->recordButton->isChecked(),
			      basic.StartRecording, "Starting recording"),
		MAKE_CALLBACK(basic.outputHandler->RecordingActive() &&
				      basic.ui->recordButton->isChecked(),
			      basic.StopRecording, "Stopping recording"),
		this, this);
	LoadHotkeyPair(recordingHotkeys, "OBSBasic.StartRecording",
		       "OBSBasic.StopRecording");
J
jp9000 已提交
2221

J
jp9000 已提交
2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232
	pauseHotkeys = obs_hotkey_pair_register_frontend(
		"OBSBasic.PauseRecording", Str("Basic.Main.PauseRecording"),
		"OBSBasic.UnpauseRecording", Str("Basic.Main.UnpauseRecording"),
		MAKE_CALLBACK(basic.pause && !basic.pause->isChecked(),
			      basic.PauseRecording, "Pausing recording"),
		MAKE_CALLBACK(basic.pause && basic.pause->isChecked(),
			      basic.UnpauseRecording, "Unpausing recording"),
		this, this);
	LoadHotkeyPair(pauseHotkeys, "OBSBasic.PauseRecording",
		       "OBSBasic.UnpauseRecording");

J
jp9000 已提交
2233
	replayBufHotkeys = obs_hotkey_pair_register_frontend(
J
jp9000 已提交
2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
		"OBSBasic.StartReplayBuffer",
		Str("Basic.Main.StartReplayBuffer"),
		"OBSBasic.StopReplayBuffer", Str("Basic.Main.StopReplayBuffer"),
		MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(),
			      basic.StartReplayBuffer,
			      "Starting replay buffer"),
		MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(),
			      basic.StopReplayBuffer, "Stopping replay buffer"),
		this, this);
	LoadHotkeyPair(replayBufHotkeys, "OBSBasic.StartReplayBuffer",
		       "OBSBasic.StopReplayBuffer");
2245 2246

	togglePreviewHotkeys = obs_hotkey_pair_register_frontend(
J
jp9000 已提交
2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
		"OBSBasic.EnablePreview",
		Str("Basic.Main.PreviewConextMenu.Enable"),
		"OBSBasic.DisablePreview", Str("Basic.Main.Preview.Disable"),
		MAKE_CALLBACK(!basic.previewEnabled, basic.EnablePreview,
			      "Enabling preview"),
		MAKE_CALLBACK(basic.previewEnabled, basic.DisablePreview,
			      "Disabling preview"),
		this, this);
	LoadHotkeyPair(togglePreviewHotkeys, "OBSBasic.EnablePreview",
		       "OBSBasic.DisablePreview");
2257
#undef MAKE_CALLBACK
2258

J
jp9000 已提交
2259 2260
	auto togglePreviewProgram = [](void *data, obs_hotkey_id,
				       obs_hotkey_t *, bool pressed) {
2261
		if (pressed)
J
jp9000 已提交
2262 2263 2264
			QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
						  "on_modeSwitch_clicked",
						  Qt::QueuedConnection);
2265 2266 2267
	};

	togglePreviewProgramHotkey = obs_hotkey_register_frontend(
J
jp9000 已提交
2268 2269 2270
		"OBSBasic.TogglePreviewProgram",
		Str("Basic.TogglePreviewProgramMode"), togglePreviewProgram,
		this);
2271 2272
	LoadHotkey(togglePreviewProgramHotkey, "OBSBasic.TogglePreviewProgram");

J
jp9000 已提交
2273 2274
	auto transition = [](void *data, obs_hotkey_id, obs_hotkey_t *,
			     bool pressed) {
2275
		if (pressed)
J
jp9000 已提交
2276 2277 2278
			QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
						  "TransitionClicked",
						  Qt::QueuedConnection);
2279 2280 2281
	};

	transitionHotkey = obs_hotkey_register_frontend(
J
jp9000 已提交
2282
		"OBSBasic.Transition", Str("Transition"), transition, this);
2283
	LoadHotkey(transitionHotkey, "OBSBasic.Transition");
C
Clayton Groeneveld 已提交
2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296

	auto resetStats = [](void *data, obs_hotkey_id, obs_hotkey_t *,
			     bool pressed) {
		if (pressed)
			QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
						  "ResetStatsHotkey",
						  Qt::QueuedConnection);
	};

	statsHotkey = obs_hotkey_register_frontend(
		"OBSBasic.ResetStats", Str("Basic.Stats.ResetStats"),
		resetStats, this);
	LoadHotkey(statsHotkey, "OBSBasic.ResetStats");
2297 2298
}

J
jp9000 已提交
2299 2300 2301 2302
void OBSBasic::ClearHotkeys()
{
	obs_hotkey_pair_unregister(streamingHotkeys);
	obs_hotkey_pair_unregister(recordingHotkeys);
J
jp9000 已提交
2303
	obs_hotkey_pair_unregister(pauseHotkeys);
J
jp9000 已提交
2304
	obs_hotkey_pair_unregister(replayBufHotkeys);
2305
	obs_hotkey_pair_unregister(togglePreviewHotkeys);
J
jp9000 已提交
2306
	obs_hotkey_unregister(forceStreamingStopHotkey);
2307 2308
	obs_hotkey_unregister(togglePreviewProgramHotkey);
	obs_hotkey_unregister(transitionHotkey);
C
Clayton Groeneveld 已提交
2309
	obs_hotkey_unregister(statsHotkey);
J
jp9000 已提交
2310 2311
}

2312 2313
OBSBasic::~OBSBasic()
{
J
jp9000 已提交
2314 2315 2316
	/* clear out UI event queue */
	QApplication::sendPostedEvents(App());

J
jp9000 已提交
2317 2318 2319
	if (updateCheckThread && updateCheckThread->isRunning())
		updateCheckThread->wait();

2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334
	delete multiviewProjectorMenu;
	delete previewProjector;
	delete studioProgramProjector;
	delete previewProjectorSource;
	delete previewProjectorMain;
	delete sourceProjector;
	delete sceneProjectorMenu;
	delete scaleFilteringMenu;
	delete colorMenu;
	delete colorWidgetAction;
	delete colorSelect;
	delete deinterlaceMenu;
	delete perSceneTransitionMenu;
	delete shortcutFilter;
	delete trayMenu;
2335 2336
	delete programOptions;
	delete program;
J
jp9000 已提交
2337

J
jp9000 已提交
2338 2339 2340 2341 2342 2343
	/* XXX: any obs data must be released before calling obs_shutdown.
	 * currently, we can't automate this with C++ RAII because of the
	 * delicate nature of obs_shutdown needing to be freed before the UI
	 * can be freed, and we have no control over the destruction order of
	 * the Qt UI stuff, so we have to manually clear any references to
	 * libobs. */
J
jp9000 已提交
2344
	delete cpuUsageTimer;
2345 2346
	os_cpu_usage_info_destroy(cpuUsageInfo);

P
Palana 已提交
2347
	obs_hotkey_set_callback_routing_func(nullptr, nullptr);
J
jp9000 已提交
2348
	ClearHotkeys();
P
Palana 已提交
2349

2350
	service = nullptr;
J
jp9000 已提交
2351 2352
	outputHandler.reset();

J
John Bradley 已提交
2353 2354 2355
	if (interaction)
		delete interaction;

2356 2357 2358
	if (properties)
		delete properties;

J
jp9000 已提交
2359 2360 2361
	if (filters)
		delete filters;

2362 2363
	if (transformWindow)
		delete transformWindow;
2364

J
jp9000 已提交
2365 2366 2367
	if (advAudioWindow)
		delete advAudioWindow;

C
cg2121 已提交
2368 2369 2370
	if (about)
		delete about;

2371
	obs_display_remove_draw_callback(ui->preview->GetDisplay(),
J
jp9000 已提交
2372
					 OBSBasic::RenderMain, this);
2373

J
jp9000 已提交
2374
	obs_enter_graphics();
2375
	gs_vertexbuffer_destroy(box);
2376 2377 2378 2379
	gs_vertexbuffer_destroy(boxLeft);
	gs_vertexbuffer_destroy(boxTop);
	gs_vertexbuffer_destroy(boxRight);
	gs_vertexbuffer_destroy(boxBottom);
2380
	gs_vertexbuffer_destroy(circle);
J
jp9000 已提交
2381
	obs_leave_graphics();
J
jp9000 已提交
2382

2383 2384 2385 2386 2387 2388 2389 2390 2391
	/* When shutting down, sometimes source references can get in to the
	 * event queue, and if we don't forcibly process those events they
	 * won't get processed until after obs_shutdown has been called.  I
	 * really wish there were a more elegant way to deal with this via C++,
	 * but Qt doesn't use C++ in a normal way, so you can't really rely on
	 * normal C++ behavior for your data to be freed in the order that you
	 * expect or want it to. */
	QApplication::sendPostedEvents(this);

J
jp9000 已提交
2392
	config_set_int(App()->GlobalConfig(), "General", "LastVersion",
J
jp9000 已提交
2393
		       LIBOBS_API_VER);
2394 2395
#if OBS_RELEASE_CANDIDATE > 0
	config_set_int(App()->GlobalConfig(), "General", "LastRCVersion",
J
jp9000 已提交
2396
		       OBS_RELEASE_CANDIDATE_VER);
2397
#endif
J
jp9000 已提交
2398

2399
	bool alwaysOnTop = IsAlwaysOnTop(this);
J
jp9000 已提交
2400

J
jp9000 已提交
2401 2402
	config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
			previewEnabled);
2403 2404
	config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
			alwaysOnTop);
2405 2406
	config_set_bool(App()->GlobalConfig(), "BasicWindow",
			"SceneDuplicationMode", sceneDuplicationMode);
J
jp9000 已提交
2407 2408
	config_set_bool(App()->GlobalConfig(), "BasicWindow", "SwapScenesMode",
			swapScenesMode);
2409 2410 2411 2412
	config_set_bool(App()->GlobalConfig(), "BasicWindow",
			"EditPropertiesMode", editPropertiesMode);
	config_set_bool(App()->GlobalConfig(), "BasicWindow",
			"PreviewProgramMode", IsPreviewProgramMode());
J
jp9000 已提交
2413 2414
	config_set_bool(App()->GlobalConfig(), "BasicWindow", "DocksLocked",
			ui->lockUI->isChecked());
2415
	config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
2416 2417 2418 2419

#ifdef _WIN32
	uint32_t winVer = GetWindowsVersion();
	if (winVer > 0 && winVer < 0x602) {
J
jp9000 已提交
2420 2421
		bool disableAero =
			config_get_bool(basicConfig, "Video", "DisableAero");
2422 2423 2424 2425 2426
		if (disableAero) {
			SetAeroEnabled(true);
		}
	}
#endif
J
jp9000 已提交
2427 2428

#ifdef BROWSER_AVAILABLE
2429
	DestroyPanelCookieManager();
J
jp9000 已提交
2430 2431 2432
	delete cef;
	cef = nullptr;
#endif
2433 2434
}

J
jp9000 已提交
2435 2436 2437 2438 2439 2440 2441 2442 2443
void OBSBasic::SaveProjectNow()
{
	if (disableSaving)
		return;

	projectChanged = true;
	SaveProjectDeferred();
}

J
jp9000 已提交
2444 2445
void OBSBasic::SaveProject()
{
J
jp9000 已提交
2446 2447 2448
	if (disableSaving)
		return;

J
jp9000 已提交
2449 2450
	projectChanged = true;
	QMetaObject::invokeMethod(this, "SaveProjectDeferred",
J
jp9000 已提交
2451
				  Qt::QueuedConnection);
J
jp9000 已提交
2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463
}

void OBSBasic::SaveProjectDeferred()
{
	if (disableSaving)
		return;

	if (!projectChanged)
		return;

	projectChanged = false;

J
jp9000 已提交
2464 2465
	const char *sceneCollection = config_get_string(
		App()->GlobalConfig(), "Basic", "SceneCollectionFile");
2466
	char savePath[512];
J
jp9000 已提交
2467 2468 2469 2470 2471 2472 2473
	char fileName[512];
	int ret;

	if (!sceneCollection)
		return;

	ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
J
jp9000 已提交
2474
		       sceneCollection);
J
jp9000 已提交
2475 2476 2477 2478
	if (ret <= 0)
		return;

	ret = GetConfigPath(savePath, sizeof(savePath), fileName);
2479 2480 2481
	if (ret <= 0)
		return;

J
jp9000 已提交
2482 2483 2484
	Save(savePath);
}

S
Shaolin 已提交
2485 2486 2487 2488 2489
OBSSource OBSBasic::GetProgramSource()
{
	return OBSGetStrongRef(programScene);
}

J
jp9000 已提交
2490
OBSScene OBSBasic::GetCurrentScene()
2491
{
J
jp9000 已提交
2492
	QListWidgetItem *item = ui->scenes->currentItem();
P
Palana 已提交
2493
	return item ? GetOBSRef<OBSScene>(item) : nullptr;
2494 2495
}

2496
OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
J
jp9000 已提交
2497
{
P
Palana 已提交
2498
	return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
J
jp9000 已提交
2499 2500
}

2501 2502
OBSSceneItem OBSBasic::GetCurrentSceneItem()
{
J
jp9000 已提交
2503
	return ui->sources->Get(GetTopSelectedSourceItem());
2504 2505
}

J
Joseph El-Khouri 已提交
2506 2507
void OBSBasic::UpdatePreviewScalingMenu()
{
2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521
	bool fixedScaling = ui->preview->IsFixedScaling();
	float scalingAmount = ui->preview->GetScalingAmount();
	if (!fixedScaling) {
		ui->actionScaleWindow->setChecked(true);
		ui->actionScaleCanvas->setChecked(false);
		ui->actionScaleOutput->setChecked(false);
		return;
	}

	obs_video_info ovi;
	obs_get_video_info(&ovi);

	ui->actionScaleWindow->setChecked(false);
	ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f);
J
jp9000 已提交
2522 2523 2524
	ui->actionScaleOutput->setChecked(scalingAmount ==
					  float(ovi.output_width) /
						  float(ovi.base_width));
J
Joseph El-Khouri 已提交
2525 2526
}

2527
void OBSBasic::CreateInteractionWindow(obs_source_t *source)
J
John Bradley 已提交
2528 2529 2530 2531 2532 2533 2534 2535 2536
{
	if (interaction)
		interaction->close();

	interaction = new OBSBasicInteraction(this, source);
	interaction->Init();
	interaction->setAttribute(Qt::WA_DeleteOnClose, true);
}

2537
void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
2538 2539 2540 2541 2542 2543 2544
{
	if (properties)
		properties->close();

	properties = new OBSBasicProperties(this, source);
	properties->Init();
	properties->setAttribute(Qt::WA_DeleteOnClose, true);
2545 2546
}

J
jp9000 已提交
2547 2548 2549 2550 2551 2552 2553 2554 2555 2556
void OBSBasic::CreateFiltersWindow(obs_source_t *source)
{
	if (filters)
		filters->close();

	filters = new OBSBasicFilters(this, source);
	filters->Init();
	filters->setAttribute(Qt::WA_DeleteOnClose, true);
}

2557 2558 2559
/* Qt callbacks for invokeMethod */

void OBSBasic::AddScene(OBSSource source)
2560
{
J
jp9000 已提交
2561
	const char *name = obs_source_get_name(source);
2562
	obs_scene_t *scene = obs_scene_from_source(source);
J
jp9000 已提交
2563 2564

	QListWidgetItem *item = new QListWidgetItem(QT_UTF8(name));
P
Palana 已提交
2565
	SetOBSRef(item, OBSScene(scene));
J
jp9000 已提交
2566
	ui->scenes->addItem(item);
2567

J
jp9000 已提交
2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582
	obs_hotkey_register_source(
		source, "OBSBasic.SelectScene",
		Str("Basic.Hotkeys.SelectScene"),
		[](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) {
			OBSBasic *main = reinterpret_cast<OBSBasic *>(
				App()->GetMainWindow());

			auto potential_source =
				static_cast<obs_source_t *>(data);
			auto source = obs_source_get_ref(potential_source);
			if (source && pressed)
				main->SetCurrentScene(source);
			obs_source_release(source);
		},
		static_cast<obs_source_t *>(source));
P
Palana 已提交
2583

2584
	signal_handler_t *handler = obs_source_get_signal_handler(source);
2585

J
jp9000 已提交
2586 2587 2588
	SignalContainer<OBSScene> container;
	container.ref = scene;
	container.handlers.assign({
2589
		std::make_shared<OBSSignal>(handler, "item_add",
J
jp9000 已提交
2590
					    OBSBasic::SceneItemAdded, this),
2591
		std::make_shared<OBSSignal>(handler, "item_select",
J
jp9000 已提交
2592
					    OBSBasic::SceneItemSelected, this),
2593
		std::make_shared<OBSSignal>(handler, "item_deselect",
J
jp9000 已提交
2594 2595
					    OBSBasic::SceneItemDeselected,
					    this),
2596
		std::make_shared<OBSSignal>(handler, "reorder",
J
jp9000 已提交
2597
					    OBSBasic::SceneReordered, this),
2598 2599
		std::make_shared<OBSSignal>(handler, "refresh",
					    OBSBasic::SceneRefreshed, this),
J
jp9000 已提交
2600
	});
2601 2602

	item->setData(static_cast<int>(QtDataRole::OBSSignals),
J
jp9000 已提交
2603
		      QVariant::fromValue(container));
J
jp9000 已提交
2604

2605
	/* if the scene already has items (a duplicated scene) add them */
J
jp9000 已提交
2606
	auto addSceneItem = [this](obs_sceneitem_t *item) {
2607 2608 2609 2610 2611
		AddSceneItem(item);
	};

	using addSceneItem_t = decltype(addSceneItem);

J
jp9000 已提交
2612 2613 2614 2615 2616 2617 2618 2619 2620
	obs_scene_enum_items(
		scene,
		[](obs_scene_t *, obs_sceneitem_t *item, void *param) {
			addSceneItem_t *func;
			func = reinterpret_cast<addSceneItem_t *>(param);
			(*func)(item);
			return true;
		},
		&addSceneItem);
2621

J
jp9000 已提交
2622
	SaveProject();
2623 2624 2625 2626

	if (!disableSaving) {
		obs_source_t *source = obs_scene_get_source(scene);
		blog(LOG_INFO, "User added scene '%s'",
J
jp9000 已提交
2627
		     obs_source_get_name(source));
S
Shaolin 已提交
2628 2629

		OBSProjector::UpdateMultiviewProjectors();
2630
	}
2631 2632 2633

	if (api)
		api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
2634 2635
}

2636
void OBSBasic::RemoveScene(OBSSource source)
J
jp9000 已提交
2637
{
P
Palana 已提交
2638 2639 2640 2641
	obs_scene_t *scene = obs_scene_from_source(source);

	QListWidgetItem *sel = nullptr;
	int count = ui->scenes->count();
2642

P
Palana 已提交
2643 2644 2645 2646 2647
	for (int i = 0; i < count; i++) {
		auto item = ui->scenes->item(i);
		auto cur_scene = GetOBSRef<OBSScene>(item);
		if (cur_scene != scene)
			continue;
J
jp9000 已提交
2648

P
Palana 已提交
2649 2650 2651
		sel = item;
		break;
	}
J
jp9000 已提交
2652

J
jp9000 已提交
2653
	if (sel != nullptr) {
P
Palana 已提交
2654
		if (sel == ui->scenes->currentItem())
J
jp9000 已提交
2655
			ui->sources->Clear();
J
jp9000 已提交
2656
		delete sel;
J
jp9000 已提交
2657
	}
J
jp9000 已提交
2658 2659

	SaveProject();
2660 2661 2662

	if (!disableSaving) {
		blog(LOG_INFO, "User Removed scene '%s'",
J
jp9000 已提交
2663
		     obs_source_get_name(source));
S
Shaolin 已提交
2664 2665

		OBSProjector::UpdateMultiviewProjectors();
2666
	}
2667 2668 2669

	if (api)
		api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
2670 2671
}

J
jp9000 已提交
2672 2673 2674
static bool select_one(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
{
	obs_sceneitem_t *selectedItem =
J
jp9000 已提交
2675
		reinterpret_cast<obs_sceneitem_t *>(param);
J
jp9000 已提交
2676 2677 2678 2679 2680 2681 2682 2683 2684
	if (obs_sceneitem_is_group(item))
		obs_sceneitem_group_enum_items(item, select_one, param);

	obs_sceneitem_select(item, (selectedItem == item));

	UNUSED_PARAMETER(scene);
	return true;
}

2685
void OBSBasic::AddSceneItem(OBSSceneItem item)
2686
{
J
jp9000 已提交
2687
	obs_scene_t *scene = obs_sceneitem_get_scene(item);
J
jp9000 已提交
2688

2689
	if (GetCurrentScene() == scene)
J
jp9000 已提交
2690
		ui->sources->Add(item);
J
jp9000 已提交
2691

J
jp9000 已提交
2692
	SaveProject();
2693 2694 2695 2696 2697

	if (!disableSaving) {
		obs_source_t *sceneSource = obs_scene_get_source(scene);
		obs_source_t *itemSource = obs_sceneitem_get_source(item);
		blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'",
J
jp9000 已提交
2698 2699 2700 2701 2702 2703
		     obs_source_get_name(itemSource),
		     obs_source_get_id(itemSource),
		     obs_source_get_name(sceneSource));

		obs_scene_enum_items(scene, select_one,
				     (obs_sceneitem_t *)item);
2704
	}
2705 2706
}

2707
void OBSBasic::UpdateSceneSelection(OBSSource source)
2708 2709
{
	if (source) {
2710
		obs_scene_t *scene = obs_scene_from_source(source);
2711
		const char *name = obs_source_get_name(source);
J
jp9000 已提交
2712

2713 2714 2715
		if (!scene)
			return;

J
jp9000 已提交
2716
		QList<QListWidgetItem *> items =
J
jp9000 已提交
2717 2718
			ui->scenes->findItems(QT_UTF8(name), Qt::MatchExactly);

2719 2720 2721 2722 2723
		if (items.count()) {
			sceneChanging = true;
			ui->scenes->setCurrentItem(items.first());
			sceneChanging = false;

2724 2725 2726
			OBSScene curScene =
				GetOBSRef<OBSScene>(ui->scenes->currentItem());
			if (api && scene != curScene)
J
jp9000 已提交
2727 2728
				api->on_event(
					OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
2729
		}
J
jp9000 已提交
2730
	}
2731 2732
}

J
jp9000 已提交
2733
static void RenameListValues(QListWidget *listWidget, const QString &newName,
J
jp9000 已提交
2734
			     const QString &prevName)
J
jp9000 已提交
2735
{
J
jp9000 已提交
2736
	QList<QListWidgetItem *> items =
J
jp9000 已提交
2737 2738 2739 2740 2741 2742
		listWidget->findItems(prevName, Qt::MatchExactly);

	for (int i = 0; i < items.count(); i++)
		items[i]->setText(newName);
}

S
Shaolin 已提交
2743
void OBSBasic::RenameSources(OBSSource source, QString newName,
J
jp9000 已提交
2744
			     QString prevName)
J
jp9000 已提交
2745
{
J
jp9000 已提交
2746
	RenameListValues(ui->scenes, newName, prevName);
2747 2748 2749 2750 2751

	for (size_t i = 0; i < volumes.size(); i++) {
		if (volumes[i]->GetName().compare(prevName) == 0)
			volumes[i]->SetName(newName);
	}
J
jp9000 已提交
2752

2753 2754 2755 2756
	for (size_t i = 0; i < projectors.size(); i++) {
		if (projectors[i]->GetSource() == source)
			projectors[i]->RenameProjector(prevName, newName);
	}
C
cg2121 已提交
2757

J
jp9000 已提交
2758
	SaveProject();
S
Shaolin 已提交
2759 2760 2761 2762

	obs_scene_t *scene = obs_scene_from_source(source);
	if (scene)
		OBSProjector::UpdateMultiviewProjectors();
J
jp9000 已提交
2763 2764
}

2765 2766
void OBSBasic::SelectSceneItem(OBSScene scene, OBSSceneItem item, bool select)
{
J
jp9000 已提交
2767 2768
	SignalBlocker sourcesSignalBlocker(ui->sources);

2769
	if (scene != GetCurrentScene() || ignoreSelectionUpdate)
2770 2771
		return;

J
jp9000 已提交
2772
	ui->sources->SelectItem(item, select);
2773 2774
}

2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790
static inline bool SourceMixerHidden(obs_source_t *source)
{
	obs_data_t *priv_settings = obs_source_get_private_settings(source);
	bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden");
	obs_data_release(priv_settings);

	return hidden;
}

static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden)
{
	obs_data_t *priv_settings = obs_source_get_private_settings(source);
	obs_data_set_bool(priv_settings, "mixer_hidden", hidden);
	obs_data_release(priv_settings);
}

2791 2792
void OBSBasic::GetAudioSourceFilters()
{
J
jp9000 已提交
2793 2794
	QAction *action = reinterpret_cast<QAction *>(sender());
	VolControl *vol = action->property("volControl").value<VolControl *>();
2795 2796 2797 2798 2799 2800 2801
	obs_source_t *source = vol->GetSource();

	CreateFiltersWindow(source);
}

void OBSBasic::GetAudioSourceProperties()
{
J
jp9000 已提交
2802 2803
	QAction *action = reinterpret_cast<QAction *>(sender());
	VolControl *vol = action->property("volControl").value<VolControl *>();
2804 2805 2806 2807 2808
	obs_source_t *source = vol->GetSource();

	CreatePropertiesWindow(source);
}

2809 2810
void OBSBasic::HideAudioControl()
{
J
jp9000 已提交
2811 2812
	QAction *action = reinterpret_cast<QAction *>(sender());
	VolControl *vol = action->property("volControl").value<VolControl *>();
2813 2814 2815 2816 2817 2818 2819 2820 2821 2822
	obs_source_t *source = vol->GetSource();

	if (!SourceMixerHidden(source)) {
		SetSourceMixerHidden(source, true);
		DeactivateAudioSource(source);
	}
}

void OBSBasic::UnhideAllAudioControls()
{
J
jp9000 已提交
2823
	auto UnhideAudioMixer = [this](obs_source_t *source) /* -- */
2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836
	{
		if (!obs_source_active(source))
			return true;
		if (!SourceMixerHidden(source))
			return true;

		SetSourceMixerHidden(source, false);
		ActivateAudioSource(source);
		return true;
	};

	using UnhideAudioMixer_t = decltype(UnhideAudioMixer);

J
jp9000 已提交
2837 2838
	auto PreEnum = [](void *data, obs_source_t *source) -> bool /* -- */
	{ return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source); };
2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856

	obs_enum_sources(PreEnum, &UnhideAudioMixer);
}

void OBSBasic::ToggleHideMixer()
{
	OBSSceneItem item = GetCurrentSceneItem();
	OBSSource source = obs_sceneitem_get_source(item);

	if (!SourceMixerHidden(source)) {
		SetSourceMixerHidden(source, true);
		DeactivateAudioSource(source);
	} else {
		SetSourceMixerHidden(source, false);
		ActivateAudioSource(source);
	}
}

2857 2858
void OBSBasic::MixerRenameSource()
{
J
jp9000 已提交
2859 2860
	QAction *action = reinterpret_cast<QAction *>(sender());
	VolControl *vol = action->property("volControl").value<VolControl *>();
2861 2862 2863 2864 2865 2866
	OBSSource source = vol->GetSource();

	const char *prevName = obs_source_get_name(source);

	for (;;) {
		string name;
J
jp9000 已提交
2867 2868 2869 2870
		bool accepted = NameDialog::AskForName(
			this, QTStr("Basic.Main.MixerRename.Title"),
			QTStr("Basic.Main.MixerRename.Text"), name,
			QT_UTF8(prevName));
2871 2872 2873 2874
		if (!accepted)
			return;

		if (name.empty()) {
2875
			OBSMessageBox::warning(this,
J
jp9000 已提交
2876 2877
					       QTStr("NoNameEntered.Title"),
					       QTStr("NoNameEntered.Text"));
2878 2879 2880
			continue;
		}

2881 2882
		OBSSource sourceTest = obs_get_source_by_name(name.c_str());
		obs_source_release(sourceTest);
2883 2884

		if (sourceTest) {
J
jp9000 已提交
2885 2886
			OBSMessageBox::warning(this, QTStr("NameExists.Title"),
					       QTStr("NameExists.Text"));
2887 2888 2889 2890 2891 2892 2893 2894
			continue;
		}

		obs_source_set_name(source, name.c_str());
		break;
	}
}

2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916
static inline bool SourceVolumeLocked(obs_source_t *source)
{
	obs_data_t *priv_settings = obs_source_get_private_settings(source);
	bool lock = obs_data_get_bool(priv_settings, "volume_locked");
	obs_data_release(priv_settings);

	return lock;
}

void OBSBasic::LockVolumeControl(bool lock)
{
	QAction *action = reinterpret_cast<QAction *>(sender());
	VolControl *vol = action->property("volControl").value<VolControl *>();
	obs_source_t *source = vol->GetSource();

	obs_data_t *priv_settings = obs_source_get_private_settings(source);
	obs_data_set_bool(priv_settings, "volume_locked", lock);
	obs_data_release(priv_settings);

	vol->EnableSlider(!lock);
}

2917 2918
void OBSBasic::VolControlContextMenu()
{
J
jp9000 已提交
2919
	VolControl *vol = reinterpret_cast<VolControl *>(sender());
2920

2921 2922
	/* ------------------- */

2923 2924 2925 2926
	QAction lockAction(QTStr("LockVolume"), this);
	lockAction.setCheckable(true);
	lockAction.setChecked(SourceVolumeLocked(vol->GetSource()));

2927 2928
	QAction hideAction(QTStr("Hide"), this);
	QAction unhideAllAction(QTStr("UnhideAll"), this);
2929
	QAction mixerRenameAction(QTStr("Rename"), this);
2930

2931 2932 2933
	QAction copyFiltersAction(QTStr("Copy.Filters"), this);
	QAction pasteFiltersAction(QTStr("Paste.Filters"), this);

2934 2935
	QAction filtersAction(QTStr("Filters"), this);
	QAction propertiesAction(QTStr("Properties"), this);
2936
	QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
2937

S
Shaolin 已提交
2938 2939
	QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
	toggleControlLayoutAction.setCheckable(true);
J
jp9000 已提交
2940 2941
	toggleControlLayoutAction.setChecked(config_get_bool(
		GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
S
Shaolin 已提交
2942

2943 2944
	/* ------------------- */

J
jp9000 已提交
2945 2946 2947 2948
	connect(&hideAction, &QAction::triggered, this,
		&OBSBasic::HideAudioControl, Qt::DirectConnection);
	connect(&unhideAllAction, &QAction::triggered, this,
		&OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
2949 2950
	connect(&lockAction, &QAction::toggled, this,
		&OBSBasic::LockVolumeControl, Qt::DirectConnection);
J
jp9000 已提交
2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965
	connect(&mixerRenameAction, &QAction::triggered, this,
		&OBSBasic::MixerRenameSource, Qt::DirectConnection);

	connect(&copyFiltersAction, &QAction::triggered, this,
		&OBSBasic::AudioMixerCopyFilters, Qt::DirectConnection);
	connect(&pasteFiltersAction, &QAction::triggered, this,
		&OBSBasic::AudioMixerPasteFilters, Qt::DirectConnection);

	connect(&filtersAction, &QAction::triggered, this,
		&OBSBasic::GetAudioSourceFilters, Qt::DirectConnection);
	connect(&propertiesAction, &QAction::triggered, this,
		&OBSBasic::GetAudioSourceProperties, Qt::DirectConnection);
	connect(&advPropAction, &QAction::triggered, this,
		&OBSBasic::on_actionAdvAudioProperties_triggered,
		Qt::DirectConnection);
2966

2967 2968
	/* ------------------- */

S
Shaolin 已提交
2969
	connect(&toggleControlLayoutAction, &QAction::changed, this,
J
jp9000 已提交
2970
		&OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
S
Shaolin 已提交
2971 2972 2973

	/* ------------------- */

2974
	hideAction.setProperty("volControl",
J
jp9000 已提交
2975
			       QVariant::fromValue<VolControl *>(vol));
2976 2977
	lockAction.setProperty("volControl",
			       QVariant::fromValue<VolControl *>(vol));
2978
	mixerRenameAction.setProperty("volControl",
J
jp9000 已提交
2979
				      QVariant::fromValue<VolControl *>(vol));
2980

2981
	copyFiltersAction.setProperty("volControl",
J
jp9000 已提交
2982
				      QVariant::fromValue<VolControl *>(vol));
2983
	pasteFiltersAction.setProperty("volControl",
J
jp9000 已提交
2984
				       QVariant::fromValue<VolControl *>(vol));
2985

2986
	filtersAction.setProperty("volControl",
J
jp9000 已提交
2987
				  QVariant::fromValue<VolControl *>(vol));
2988
	propertiesAction.setProperty("volControl",
J
jp9000 已提交
2989
				     QVariant::fromValue<VolControl *>(vol));
2990

2991 2992
	/* ------------------- */

2993 2994 2995 2996 2997
	if (copyFiltersString == nullptr)
		pasteFiltersAction.setEnabled(false);
	else
		pasteFiltersAction.setEnabled(true);

2998
	QMenu popup;
2999 3000
	popup.addAction(&lockAction);
	popup.addSeparator();
3001 3002
	popup.addAction(&unhideAllAction);
	popup.addAction(&hideAction);
3003
	popup.addAction(&mixerRenameAction);
3004
	popup.addSeparator();
3005 3006 3007
	popup.addAction(&copyFiltersAction);
	popup.addAction(&pasteFiltersAction);
	popup.addSeparator();
S
Shaolin 已提交
3008 3009
	popup.addAction(&toggleControlLayoutAction);
	popup.addSeparator();
3010 3011
	popup.addAction(&filtersAction);
	popup.addAction(&propertiesAction);
3012
	popup.addAction(&advPropAction);
3013 3014 3015
	popup.exec(QCursor::pos());
}

S
Shaolin 已提交
3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026
void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
{
	StackedMixerAreaContextMenuRequested();
}

void OBSBasic::on_vMixerScrollArea_customContextMenuRequested()
{
	StackedMixerAreaContextMenuRequested();
}

void OBSBasic::StackedMixerAreaContextMenuRequested()
3027 3028
{
	QAction unhideAllAction(QTStr("UnhideAll"), this);
S
SuslikV 已提交
3029 3030 3031

	QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);

S
Shaolin 已提交
3032 3033
	QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
	toggleControlLayoutAction.setCheckable(true);
J
jp9000 已提交
3034 3035
	toggleControlLayoutAction.setChecked(config_get_bool(
		GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
S
Shaolin 已提交
3036

S
SuslikV 已提交
3037 3038
	/* ------------------- */

J
jp9000 已提交
3039 3040
	connect(&unhideAllAction, &QAction::triggered, this,
		&OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
3041

J
jp9000 已提交
3042 3043 3044
	connect(&advPropAction, &QAction::triggered, this,
		&OBSBasic::on_actionAdvAudioProperties_triggered,
		Qt::DirectConnection);
S
SuslikV 已提交
3045 3046 3047

	/* ------------------- */

S
Shaolin 已提交
3048
	connect(&toggleControlLayoutAction, &QAction::changed, this,
J
jp9000 已提交
3049
		&OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
S
Shaolin 已提交
3050 3051 3052

	/* ------------------- */

3053
	QMenu popup;
3054
	popup.addAction(&unhideAllAction);
S
SuslikV 已提交
3055
	popup.addSeparator();
S
Shaolin 已提交
3056 3057
	popup.addAction(&toggleControlLayoutAction);
	popup.addSeparator();
S
SuslikV 已提交
3058
	popup.addAction(&advPropAction);
3059 3060 3061
	popup.exec(QCursor::pos());
}

3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072
void OBSBasic::ToggleMixerLayout(bool vertical)
{
	if (vertical) {
		ui->stackedMixerArea->setMinimumSize(180, 220);
		ui->stackedMixerArea->setCurrentIndex(1);
	} else {
		ui->stackedMixerArea->setMinimumSize(220, 0);
		ui->stackedMixerArea->setCurrentIndex(0);
	}
}

S
Shaolin 已提交
3073 3074 3075
void OBSBasic::ToggleVolControlLayout()
{
	bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
J
jp9000 已提交
3076
					 "VerticalVolControl");
S
Shaolin 已提交
3077 3078
	config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
			vertical);
3079
	ToggleMixerLayout(vertical);
S
Shaolin 已提交
3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092

	// We need to store it so we can delete current and then add
	// at the right order
	vector<OBSSource> sources;
	for (size_t i = 0; i != volumes.size(); i++)
		sources.emplace_back(volumes[i]->GetSource());

	ClearVolumeControls();

	for (const auto &source : sources)
		ActivateAudioSource(source);
}

3093 3094
void OBSBasic::ActivateAudioSource(OBSSource source)
{
3095 3096
	if (SourceMixerHidden(source))
		return;
3097 3098
	if (!obs_source_audio_active(source))
		return;
3099

S
Shaolin 已提交
3100
	bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
J
jp9000 已提交
3101
					"VerticalVolControl");
S
Shaolin 已提交
3102
	VolControl *vol = new VolControl(source, true, vertical);
3103

3104 3105
	vol->EnableSlider(!SourceVolumeLocked(source));

J
jp9000 已提交
3106 3107
	double meterDecayRate =
		config_get_double(basicConfig, "Audio", "MeterDecayRate");
S
Shaolin 已提交
3108
	vol->SetMeterDecayRate(meterDecayRate);
3109

J
jp9000 已提交
3110 3111
	uint32_t peakMeterTypeIdx =
		config_get_uint(basicConfig, "Audio", "PeakMeterType");
3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127

	enum obs_peak_meter_type peakMeterType;
	switch (peakMeterTypeIdx) {
	case 0:
		peakMeterType = SAMPLE_PEAK_METER;
		break;
	case 1:
		peakMeterType = TRUE_PEAK_METER;
		break;
	default:
		peakMeterType = SAMPLE_PEAK_METER;
		break;
	}

	vol->setPeakMeterType(peakMeterType);

3128 3129
	vol->setContextMenuPolicy(Qt::CustomContextMenu);

J
jp9000 已提交
3130 3131 3132 3133
	connect(vol, &QWidget::customContextMenuRequested, this,
		&OBSBasic::VolControlContextMenu);
	connect(vol, &VolControl::ConfigClicked, this,
		&OBSBasic::VolControlContextMenu);
3134

3135 3136 3137
	InsertQObjectByName(volumes, vol);

	for (auto volume : volumes) {
S
Shaolin 已提交
3138 3139 3140 3141
		if (vertical)
			ui->vVolControlLayout->addWidget(volume);
		else
			ui->hVolControlLayout->addWidget(volume);
3142
	}
3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155
}

void OBSBasic::DeactivateAudioSource(OBSSource source)
{
	for (size_t i = 0; i < volumes.size(); i++) {
		if (volumes[i]->GetSource() == source) {
			delete volumes[i];
			volumes.erase(volumes.begin() + i);
			break;
		}
	}
}

3156
bool OBSBasic::QueryRemoveSource(obs_source_t *source)
J
jp9000 已提交
3157
{
J
jp9000 已提交
3158
	if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
3159
	    !obs_source_is_group(source)) {
3160 3161 3162
		int count = ui->scenes->count();

		if (count == 1) {
3163
			OBSMessageBox::information(this,
J
jp9000 已提交
3164 3165
						   QTStr("FinalScene.Title"),
						   QTStr("FinalScene.Text"));
3166 3167
			return false;
		}
3168 3169
	}

J
jp9000 已提交
3170
	const char *name = obs_source_get_name(source);
3171 3172 3173

	QString text = QTStr("ConfirmRemove.Text");
	text.replace("$1", QT_UTF8(name));
J
jp9000 已提交
3174

3175
	QMessageBox remove_source(this);
3176
	remove_source.setText(text);
J
jp9000 已提交
3177 3178
	QAbstractButton *Yes =
		remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole);
J
Jkoan 已提交
3179 3180 3181 3182 3183 3184
	remove_source.addButton(QTStr("No"), QMessageBox::NoRole);
	remove_source.setIcon(QMessageBox::Question);
	remove_source.setWindowTitle(QTStr("ConfirmRemove.Title"));
	remove_source.exec();

	return Yes == remove_source.clickedButton();
3185
}
J
jp9000 已提交
3186

J
jp9000 已提交
3187
#define UPDATE_CHECK_INTERVAL (60 * 60 * 24 * 4) /* 4 days */
J
jp9000 已提交
3188

P
Palana 已提交
3189 3190 3191 3192 3193
#ifdef UPDATE_SPARKLE
void init_sparkle_updater(bool update_to_undeployed);
void trigger_sparkle_update();
#endif

J
jp9000 已提交
3194 3195
void OBSBasic::TimedCheckForUpdates()
{
J
jp9000 已提交
3196
	if (!config_get_bool(App()->GlobalConfig(), "General",
J
jp9000 已提交
3197
			     "EnableAutoUpdates"))
J
jp9000 已提交
3198 3199
		return;

P
Palana 已提交
3200 3201
#ifdef UPDATE_SPARKLE
	init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
J
jp9000 已提交
3202
					     "UpdateToUndeployed"));
3203
#elif _WIN32
J
jp9000 已提交
3204
	long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
J
jp9000 已提交
3205 3206 3207
					      "LastUpdateCheck");
	uint32_t lastVersion =
		config_get_int(App()->GlobalConfig(), "General", "LastVersion");
J
jp9000 已提交
3208 3209 3210 3211

	if (lastVersion < LIBOBS_API_VER) {
		lastUpdate = 0;
		config_set_int(App()->GlobalConfig(), "General",
J
jp9000 已提交
3212
			       "LastUpdateCheck", 0);
J
jp9000 已提交
3213 3214
	}

J
jp9000 已提交
3215
	long long t = (long long)time(nullptr);
J
jp9000 已提交
3216 3217 3218
	long long secs = t - lastUpdate;

	if (secs > UPDATE_CHECK_INTERVAL)
J
jp9000 已提交
3219
		CheckForUpdates(false);
P
Palana 已提交
3220
#endif
J
jp9000 已提交
3221 3222
}

J
jp9000 已提交
3223
void OBSBasic::CheckForUpdates(bool manualUpdate)
J
jp9000 已提交
3224
{
P
Palana 已提交
3225 3226
#ifdef UPDATE_SPARKLE
	trigger_sparkle_update();
3227
#elif _WIN32
J
jp9000 已提交
3228 3229
	ui->actionCheckForUpdates->setEnabled(false);

J
jp9000 已提交
3230 3231
	if (updateCheckThread && updateCheckThread->isRunning())
		return;
3232

3233
	updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
3234
	updateCheckThread->start();
P
Palana 已提交
3235
#endif
3236 3237

	UNUSED_PARAMETER(manualUpdate);
J
jp9000 已提交
3238 3239
}

J
jp9000 已提交
3240
void OBSBasic::updateCheckFinished()
J
jp9000 已提交
3241 3242 3243 3244
{
	ui->actionCheckForUpdates->setEnabled(true);
}

3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265
void OBSBasic::DuplicateSelectedScene()
{
	OBSScene curScene = GetCurrentScene();

	if (!curScene)
		return;

	OBSSource curSceneSource = obs_scene_get_source(curScene);
	QString format{obs_source_get_name(curSceneSource)};
	format += " %1";

	int i = 2;
	QString placeHolderText = format.arg(i);
	obs_source_t *source = nullptr;
	while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
		obs_source_release(source);
		placeHolderText = format.arg(++i);
	}

	for (;;) {
		string name;
J
jp9000 已提交
3266 3267 3268 3269
		bool accepted = NameDialog::AskForName(
			this, QTStr("Basic.Main.AddSceneDlg.Title"),
			QTStr("Basic.Main.AddSceneDlg.Text"), name,
			placeHolderText);
3270 3271 3272 3273
		if (!accepted)
			return;

		if (name.empty()) {
3274
			OBSMessageBox::warning(this,
J
jp9000 已提交
3275 3276
					       QTStr("NoNameEntered.Title"),
					       QTStr("NoNameEntered.Text"));
3277 3278 3279 3280 3281
			continue;
		}

		obs_source_t *source = obs_get_source_by_name(name.c_str());
		if (source) {
J
jp9000 已提交
3282 3283
			OBSMessageBox::warning(this, QTStr("NameExists.Title"),
					       QTStr("NameExists.Text"));
3284 3285 3286 3287 3288

			obs_source_release(source);
			continue;
		}

J
jp9000 已提交
3289 3290
		obs_scene_t *scene = obs_scene_duplicate(curScene, name.c_str(),
							 OBS_SCENE_DUP_REFS);
3291
		source = obs_scene_get_source(scene);
3292
		SetCurrentScene(source, true);
3293
		obs_scene_release(scene);
J
jp9000 已提交
3294

3295
		break;
3296 3297 3298
	}
}

3299 3300 3301 3302
void OBSBasic::RemoveSelectedScene()
{
	OBSScene scene = GetCurrentScene();
	if (scene) {
3303
		obs_source_t *source = obs_scene_get_source(scene);
J
jp9000 已提交
3304
		if (QueryRemoveSource(source)) {
3305
			obs_source_remove(source);
J
jp9000 已提交
3306 3307

			if (api)
J
jp9000 已提交
3308 3309
				api->on_event(
					OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
J
jp9000 已提交
3310
		}
3311 3312 3313 3314 3315 3316 3317
	}
}

void OBSBasic::RemoveSelectedSceneItem()
{
	OBSSceneItem item = GetCurrentSceneItem();
	if (item) {
3318
		obs_source_t *source = obs_sceneitem_get_source(item);
3319
		if (QueryRemoveSource(source))
J
jp9000 已提交
3320 3321 3322 3323
			obs_sceneitem_remove(item);
	}
}

3324 3325
void OBSBasic::ReorderSources(OBSScene scene)
{
3326
	if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
3327 3328
		return;

J
jp9000 已提交
3329
	ui->sources->ReorderItems();
J
jp9000 已提交
3330
	SaveProject();
3331 3332
}

3333 3334 3335 3336 3337 3338 3339 3340 3341
void OBSBasic::RefreshSources(OBSScene scene)
{
	if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
		return;

	ui->sources->RefreshItems();
	SaveProject();
}

3342 3343
/* OBS Callbacks */

3344 3345
void OBSBasic::SceneReordered(void *data, calldata_t *params)
{
J
jp9000 已提交
3346
	OBSBasic *window = static_cast<OBSBasic *>(data);
3347

J
jp9000 已提交
3348
	obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
3349 3350

	QMetaObject::invokeMethod(window, "ReorderSources",
J
jp9000 已提交
3351
				  Q_ARG(OBSScene, OBSScene(scene)));
3352 3353
}

3354 3355 3356 3357 3358 3359 3360 3361 3362 3363
void OBSBasic::SceneRefreshed(void *data, calldata_t *params)
{
	OBSBasic *window = static_cast<OBSBasic *>(data);

	obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");

	QMetaObject::invokeMethod(window, "RefreshSources",
				  Q_ARG(OBSScene, OBSScene(scene)));
}

3364
void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
3365
{
J
jp9000 已提交
3366
	OBSBasic *window = static_cast<OBSBasic *>(data);
3367

J
jp9000 已提交
3368
	obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
J
jp9000 已提交
3369

3370
	QMetaObject::invokeMethod(window, "AddSceneItem",
J
jp9000 已提交
3371
				  Q_ARG(OBSSceneItem, OBSSceneItem(item)));
J
jp9000 已提交
3372 3373
}

3374 3375
void OBSBasic::SceneItemSelected(void *data, calldata_t *params)
{
J
jp9000 已提交
3376
	OBSBasic *window = static_cast<OBSBasic *>(data);
3377

J
jp9000 已提交
3378 3379
	obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
	obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
3380 3381

	QMetaObject::invokeMethod(window, "SelectSceneItem",
J
jp9000 已提交
3382 3383
				  Q_ARG(OBSScene, scene),
				  Q_ARG(OBSSceneItem, item), Q_ARG(bool, true));
3384 3385 3386 3387
}

void OBSBasic::SceneItemDeselected(void *data, calldata_t *params)
{
J
jp9000 已提交
3388
	OBSBasic *window = static_cast<OBSBasic *>(data);
3389

J
jp9000 已提交
3390 3391
	obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
	obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
3392 3393

	QMetaObject::invokeMethod(window, "SelectSceneItem",
J
jp9000 已提交
3394 3395 3396
				  Q_ARG(OBSScene, scene),
				  Q_ARG(OBSSceneItem, item),
				  Q_ARG(bool, false));
3397 3398
}

3399
void OBSBasic::SourceCreated(void *data, calldata_t *params)
3400
{
J
jp9000 已提交
3401
	obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
3402

3403
	if (obs_scene_from_source(source) != NULL)
J
jp9000 已提交
3404 3405 3406
		QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
					  "AddScene", WaitConnection(),
					  Q_ARG(OBSSource, OBSSource(source)));
3407 3408
}

3409
void OBSBasic::SourceRemoved(void *data, calldata_t *params)
3410
{
J
jp9000 已提交
3411
	obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
3412

3413
	if (obs_scene_from_source(source) != NULL)
J
jp9000 已提交
3414 3415 3416
		QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
					  "RemoveScene",
					  Q_ARG(OBSSource, OBSSource(source)));
3417 3418
}

3419
void OBSBasic::SourceActivated(void *data, calldata_t *params)
3420
{
J
jp9000 已提交
3421 3422
	obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
	uint32_t flags = obs_source_get_output_flags(source);
3423 3424

	if (flags & OBS_SOURCE_AUDIO)
J
jp9000 已提交
3425 3426 3427
		QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
					  "ActivateAudioSource",
					  Q_ARG(OBSSource, OBSSource(source)));
3428 3429
}

3430
void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
3431
{
J
jp9000 已提交
3432 3433
	obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
	uint32_t flags = obs_source_get_output_flags(source);
3434 3435

	if (flags & OBS_SOURCE_AUDIO)
J
jp9000 已提交
3436 3437 3438
		QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
					  "DeactivateAudioSource",
					  Q_ARG(OBSSource, OBSSource(source)));
3439 3440
}

3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458
void OBSBasic::SourceAudioActivated(void *data, calldata_t *params)
{
	obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");

	if (obs_source_active(source))
		QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
					  "ActivateAudioSource",
					  Q_ARG(OBSSource, OBSSource(source)));
}

void OBSBasic::SourceAudioDeactivated(void *data, calldata_t *params)
{
	obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
	QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
				  "DeactivateAudioSource",
				  Q_ARG(OBSSource, OBSSource(source)));
}

3459
void OBSBasic::SourceRenamed(void *data, calldata_t *params)
J
jp9000 已提交
3460
{
J
jp9000 已提交
3461 3462
	obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
	const char *newName = calldata_string(params, "new_name");
J
jp9000 已提交
3463 3464
	const char *prevName = calldata_string(params, "prev_name");

J
jp9000 已提交
3465 3466 3467 3468
	QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
				  "RenameSources", Q_ARG(OBSSource, source),
				  Q_ARG(QString, QT_UTF8(newName)),
				  Q_ARG(QString, QT_UTF8(prevName)));
3469 3470

	blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName);
J
jp9000 已提交
3471 3472
}

3473 3474 3475 3476 3477
void OBSBasic::DrawBackdrop(float cx, float cy)
{
	if (!box)
		return;

3478 3479
	GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawBackdrop");

J
jp9000 已提交
3480 3481 3482
	gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID);
	gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color");
	gs_technique_t *tech = gs_effect_get_technique(solid, "Solid");
3483 3484 3485

	vec4 colorVal;
	vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
3486
	gs_effect_set_vec4(color, &colorVal);
3487

3488 3489
	gs_technique_begin(tech);
	gs_technique_begin_pass(tech, 0);
3490 3491 3492 3493 3494 3495 3496 3497
	gs_matrix_push();
	gs_matrix_identity();
	gs_matrix_scale3f(float(cx), float(cy), 1.0f);

	gs_load_vertexbuffer(box);
	gs_draw(GS_TRISTRIP, 0, 0);

	gs_matrix_pop();
3498 3499
	gs_technique_end_pass(tech);
	gs_technique_end(tech);
3500 3501

	gs_load_vertexbuffer(nullptr);
3502 3503

	GS_DEBUG_MARKER_END();
3504 3505
}

3506 3507
void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
{
3508 3509
	GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "RenderMain");

J
jp9000 已提交
3510
	OBSBasic *window = static_cast<OBSBasic *>(data);
3511 3512 3513 3514
	obs_video_info ovi;

	obs_get_video_info(&ovi);

J
jp9000 已提交
3515 3516
	window->previewCX = int(window->previewScale * float(ovi.base_width));
	window->previewCY = int(window->previewScale * float(ovi.base_height));
3517 3518 3519

	gs_viewport_push();
	gs_projection_push();
3520

3521 3522 3523
	obs_display_t *display = window->ui->preview->GetDisplay();
	uint32_t width, height;
	obs_display_size(display, &width, &height);
J
jp9000 已提交
3524
	float right = float(width) - window->previewX;
3525
	float bottom = float(height) - window->previewY;
3526

J
jp9000 已提交
3527 3528
	gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
		 100.0f);
3529 3530 3531

	window->ui->preview->DrawOverflow();

3532 3533
	/* --------------------------------------- */

3534
	gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
J
jp9000 已提交
3535 3536 3537
		 -100.0f, 100.0f);
	gs_set_viewport(window->previewX, window->previewY, window->previewCX,
			window->previewCY);
3538

3539
	if (window->IsPreviewProgramMode()) {
3540 3541 3542
		window->DrawBackdrop(float(ovi.base_width),
				     float(ovi.base_height));

3543 3544 3545 3546 3547
		OBSScene scene = window->GetCurrentScene();
		obs_source_t *source = obs_scene_get_source(scene);
		if (source)
			obs_source_video_render(source);
	} else {
3548
		obs_render_main_texture_src_color_only();
3549
	}
3550
	gs_load_vertexbuffer(nullptr);
3551

3552 3553
	/* --------------------------------------- */

J
jp9000 已提交
3554 3555
	gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
		 100.0f);
3556
	gs_reset_viewport();
J
jp9000 已提交
3557 3558 3559

	window->ui->preview->DrawSceneEditing();

3560 3561
	/* --------------------------------------- */

3562 3563
	gs_projection_pop();
	gs_viewport_pop();
J
jp9000 已提交
3564

3565 3566
	GS_DEBUG_MARKER_END();

J
jp9000 已提交
3567 3568
	UNUSED_PARAMETER(cx);
	UNUSED_PARAMETER(cy);
3569 3570
}

3571 3572
/* Main class functions */

3573
obs_service_t *OBSBasic::GetService()
3574
{
3575
	if (!service) {
J
jp9000 已提交
3576 3577
		service =
			obs_service_create("rtmp_common", NULL, NULL, nullptr);
3578 3579
		obs_service_release(service);
	}
3580 3581 3582
	return service;
}

3583
void OBSBasic::SetService(obs_service_t *newService)
3584
{
3585
	if (newService)
3586 3587 3588
		service = newService;
}

V
VodBox 已提交
3589 3590 3591 3592 3593
int OBSBasic::GetTransitionDuration()
{
	return ui->transitionDuration->value();
}

3594
bool OBSBasic::StreamingActive() const
3595 3596 3597 3598 3599 3600
{
	if (!outputHandler)
		return false;
	return outputHandler->StreamingActive();
}

3601 3602 3603 3604 3605 3606 3607
bool OBSBasic::Active() const
{
	if (!outputHandler)
		return false;
	return outputHandler->Active();
}

3608 3609 3610 3611 3612 3613
#ifdef _WIN32
#define IS_WIN32 1
#else
#define IS_WIN32 0
#endif

3614 3615
static inline int AttemptToResetVideo(struct obs_video_info *ovi)
{
3616
	return obs_reset_video(ovi);
3617 3618
}

3619 3620
static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
{
J
jp9000 已提交
3621 3622
	const char *scaleTypeStr =
		config_get_string(basicConfig, "Video", "ScaleType");
3623 3624 3625 3626 3627

	if (astrcmpi(scaleTypeStr, "bilinear") == 0)
		return OBS_SCALE_BILINEAR;
	else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
		return OBS_SCALE_LANCZOS;
3628 3629
	else if (astrcmpi(scaleTypeStr, "area") == 0)
		return OBS_SCALE_AREA;
3630 3631 3632 3633
	else
		return OBS_SCALE_BICUBIC;
}

3634 3635 3636 3637 3638 3639
static inline enum video_format GetVideoFormatFromName(const char *name)
{
	if (astrcmpi(name, "I420") == 0)
		return VIDEO_FORMAT_I420;
	else if (astrcmpi(name, "NV12") == 0)
		return VIDEO_FORMAT_NV12;
J
jp9000 已提交
3640 3641
	else if (astrcmpi(name, "I444") == 0)
		return VIDEO_FORMAT_I444;
3642 3643 3644 3645 3646 3647 3648 3649 3650
#if 0 //currently unsupported
	else if (astrcmpi(name, "YVYU") == 0)
		return VIDEO_FORMAT_YVYU;
	else if (astrcmpi(name, "YUY2") == 0)
		return VIDEO_FORMAT_YUY2;
	else if (astrcmpi(name, "UYVY") == 0)
		return VIDEO_FORMAT_UYVY;
#endif
	else
J
jp9000 已提交
3651
		return VIDEO_FORMAT_RGBA;
3652 3653
}

3654 3655
void OBSBasic::ResetUI()
{
J
jp9000 已提交
3656 3657
	bool studioPortraitLayout = config_get_bool(
		GetGlobalConfig(), "BasicWindow", "StudioPortraitLayout");
3658

J
jp9000 已提交
3659 3660
	bool labels = config_get_bool(GetGlobalConfig(), "BasicWindow",
				      "StudioModeLabels");
3661

3662 3663 3664 3665
	if (studioPortraitLayout)
		ui->previewLayout->setDirection(QBoxLayout::TopToBottom);
	else
		ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
3666 3667 3668 3669 3670 3671

	if (previewProgramMode)
		ui->previewLabel->setHidden(!labels);

	if (programLabel)
		programLabel->setHidden(!labels);
3672 3673
}

3674
int OBSBasic::ResetVideo()
J
jp9000 已提交
3675
{
3676 3677 3678
	if (outputHandler && outputHandler->Active())
		return OBS_VIDEO_CURRENTLY_ACTIVE;

P
Palana 已提交
3679 3680
	ProfileScope("OBSBasic::ResetVideo");

J
jp9000 已提交
3681
	struct obs_video_info ovi;
3682
	int ret;
J
jp9000 已提交
3683

3684
	GetConfigFPS(ovi.fps_num, ovi.fps_den);
J
jp9000 已提交
3685

J
jp9000 已提交
3686 3687 3688 3689 3690 3691
	const char *colorFormat =
		config_get_string(basicConfig, "Video", "ColorFormat");
	const char *colorSpace =
		config_get_string(basicConfig, "Video", "ColorSpace");
	const char *colorRange =
		config_get_string(basicConfig, "Video", "ColorRange");
3692

J
jp9000 已提交
3693
	ovi.graphics_module = App()->GetRenderModule();
J
jp9000 已提交
3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708
	ovi.base_width =
		(uint32_t)config_get_uint(basicConfig, "Video", "BaseCX");
	ovi.base_height =
		(uint32_t)config_get_uint(basicConfig, "Video", "BaseCY");
	ovi.output_width =
		(uint32_t)config_get_uint(basicConfig, "Video", "OutputCX");
	ovi.output_height =
		(uint32_t)config_get_uint(basicConfig, "Video", "OutputCY");
	ovi.output_format = GetVideoFormatFromName(colorFormat);
	ovi.colorspace = astrcmpi(colorSpace, "601") == 0 ? VIDEO_CS_601
							  : VIDEO_CS_709;
	ovi.range = astrcmpi(colorRange, "Full") == 0 ? VIDEO_RANGE_FULL
						      : VIDEO_RANGE_PARTIAL;
	ovi.adapter =
		config_get_uint(App()->GlobalConfig(), "Video", "AdapterIdx");
J
jp9000 已提交
3709
	ovi.gpu_conversion = true;
J
jp9000 已提交
3710
	ovi.scale_type = GetScaleType(basicConfig);
3711

3712
	if (ovi.base_width < 8 || ovi.base_height < 8) {
3713 3714 3715 3716 3717 3718
		ovi.base_width = 1920;
		ovi.base_height = 1080;
		config_set_uint(basicConfig, "Video", "BaseCX", 1920);
		config_set_uint(basicConfig, "Video", "BaseCY", 1080);
	}

3719
	if (ovi.output_width < 8 || ovi.output_height < 8) {
3720 3721 3722 3723 3724 3725 3726 3727
		ovi.output_width = ovi.base_width;
		ovi.output_height = ovi.base_height;
		config_set_uint(basicConfig, "Video", "OutputCX",
				ovi.base_width);
		config_set_uint(basicConfig, "Video", "OutputCY",
				ovi.base_height);
	}

3728
	ret = AttemptToResetVideo(&ovi);
3729
	if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
3730 3731
		if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
			blog(LOG_WARNING, "Tried to reset when "
J
jp9000 已提交
3732
					  "already active");
3733 3734 3735
			return ret;
		}

3736
		/* Try OpenGL if DirectX fails on windows */
3737
		if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
J
jp9000 已提交
3738 3739 3740 3741 3742
			blog(LOG_WARNING,
			     "Failed to initialize obs video (%d) "
			     "with graphics_module='%s', retrying "
			     "with graphics_module='%s'",
			     ret, ovi.graphics_module, DL_OPENGL);
3743
			ovi.graphics_module = DL_OPENGL;
3744 3745
			ret = AttemptToResetVideo(&ovi);
		}
3746 3747
	} else if (ret == OBS_VIDEO_SUCCESS) {
		ResizePreview(ovi.base_width, ovi.base_height);
3748 3749
		if (program)
			ResizeProgram(ovi.base_width, ovi.base_height);
3750 3751
	}

3752
	if (ret == OBS_VIDEO_SUCCESS) {
3753
		OBSBasicStats::InitializeValues();
3754 3755
		OBSProjector::UpdateMultiviewProjectors();
	}
3756

3757
	return ret;
J
jp9000 已提交
3758
}
J
jp9000 已提交
3759

3760
bool OBSBasic::ResetAudio()
J
jp9000 已提交
3761
{
P
Palana 已提交
3762 3763
	ProfileScope("OBSBasic::ResetAudio");

3764
	struct obs_audio_info ai;
J
jp9000 已提交
3765 3766
	ai.samples_per_sec =
		config_get_uint(basicConfig, "Audio", "SampleRate");
3767

J
jp9000 已提交
3768 3769
	const char *channelSetupStr =
		config_get_string(basicConfig, "Audio", "ChannelSetup");
3770 3771 3772

	if (strcmp(channelSetupStr, "Mono") == 0)
		ai.speakers = SPEAKERS_MONO;
P
pkviet 已提交
3773 3774
	else if (strcmp(channelSetupStr, "2.1") == 0)
		ai.speakers = SPEAKERS_2POINT1;
P
pkviet 已提交
3775 3776
	else if (strcmp(channelSetupStr, "4.0") == 0)
		ai.speakers = SPEAKERS_4POINT0;
P
pkviet 已提交
3777 3778 3779 3780 3781 3782
	else if (strcmp(channelSetupStr, "4.1") == 0)
		ai.speakers = SPEAKERS_4POINT1;
	else if (strcmp(channelSetupStr, "5.1") == 0)
		ai.speakers = SPEAKERS_5POINT1;
	else if (strcmp(channelSetupStr, "7.1") == 0)
		ai.speakers = SPEAKERS_7POINT1;
3783 3784 3785
	else
		ai.speakers = SPEAKERS_STEREO;

J
jp9000 已提交
3786
	return obs_reset_audio(&ai);
J
jp9000 已提交
3787 3788
}

3789
void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
J
jp9000 已提交
3790
				const char *deviceDesc, int channel)
J
jp9000 已提交
3791
{
3792
	bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
3793 3794
	obs_source_t *source;
	obs_data_t *settings;
J
jp9000 已提交
3795 3796 3797

	source = obs_get_output_source(channel);
	if (source) {
3798 3799 3800 3801
		if (disable) {
			obs_set_output_source(channel, nullptr);
		} else {
			settings = obs_source_get_settings(source);
J
jp9000 已提交
3802 3803
			const char *oldId =
				obs_data_get_string(settings, "device_id");
3804 3805
			if (strcmp(oldId, deviceId) != 0) {
				obs_data_set_string(settings, "device_id",
J
jp9000 已提交
3806
						    deviceId);
3807 3808 3809 3810
				obs_source_update(source, settings);
			}
			obs_data_release(settings);
		}
J
jp9000 已提交
3811 3812 3813

		obs_source_release(source);

3814 3815
	} else if (!disable) {
		settings = obs_data_create();
J
jp9000 已提交
3816
		obs_data_set_string(settings, "device_id", deviceId);
3817
		source = obs_source_create(sourceId, deviceDesc, settings,
J
jp9000 已提交
3818
					   nullptr);
J
jp9000 已提交
3819 3820 3821 3822 3823 3824 3825
		obs_data_release(settings);

		obs_set_output_source(channel, source);
		obs_source_release(source);
	}
}

J
jp9000 已提交
3826
void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
3827
{
J
jp9000 已提交
3828
	QSize targetSize;
3829
	bool isFixedScaling;
J
Joseph El-Khouri 已提交
3830
	obs_video_info ovi;
J
jp9000 已提交
3831

3832
	/* resize preview panel to fix to the top section of the window */
3833
	targetSize = GetPixelSize(ui->preview);
J
Joseph El-Khouri 已提交
3834

3835
	isFixedScaling = ui->preview->IsFixedScaling();
J
Joseph El-Khouri 已提交
3836 3837
	obs_get_video_info(&ovi);

3838 3839
	if (isFixedScaling) {
		previewScale = ui->preview->GetScalingAmount();
J
jp9000 已提交
3840 3841 3842 3843 3844
		GetCenterPosFromFixedScale(
			int(cx), int(cy),
			targetSize.width() - PREVIEW_EDGE_SIZE * 2,
			targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX,
			previewY, previewScale);
3845 3846
		previewX += ui->preview->GetScrollX();
		previewY += ui->preview->GetScrollY();
J
Joseph El-Khouri 已提交
3847 3848 3849

	} else {
		GetScaleAndCenterPos(int(cx), int(cy),
J
jp9000 已提交
3850 3851 3852 3853
				     targetSize.width() - PREVIEW_EDGE_SIZE * 2,
				     targetSize.height() -
					     PREVIEW_EDGE_SIZE * 2,
				     previewX, previewY, previewScale);
J
Joseph El-Khouri 已提交
3854
	}
J
jp9000 已提交
3855

3856 3857
	previewX += float(PREVIEW_EDGE_SIZE);
	previewY += float(PREVIEW_EDGE_SIZE);
J
jp9000 已提交
3858 3859
}

3860 3861
void OBSBasic::CloseDialogs()
{
J
jp9000 已提交
3862
	QList<QDialog *> childDialogs = this->findChildren<QDialog *>();
3863 3864 3865 3866 3867 3868
	if (!childDialogs.isEmpty()) {
		for (int i = 0; i < childDialogs.size(); ++i) {
			childDialogs.at(i)->close();
		}
	}

J
jp9000 已提交
3869 3870 3871 3872
	if (!stats.isNull())
		stats->close(); //call close to save Stats geometry
	if (!remux.isNull())
		remux->close();
3873 3874
}

3875 3876 3877 3878 3879 3880 3881
void OBSBasic::EnumDialogs()
{
	visDialogs.clear();
	modalDialogs.clear();
	visMsgBoxes.clear();

	/* fill list of Visible dialogs and Modal dialogs */
J
jp9000 已提交
3882
	QList<QDialog *> dialogs = findChildren<QDialog *>();
3883 3884 3885 3886 3887 3888 3889 3890
	for (QDialog *dialog : dialogs) {
		if (dialog->isVisible())
			visDialogs.append(dialog);
		if (dialog->isModal())
			modalDialogs.append(dialog);
	}

	/* fill list of Visible message boxes */
J
jp9000 已提交
3891
	QList<QMessageBox *> msgBoxes = findChildren<QMessageBox *>();
3892 3893 3894 3895 3896 3897
	for (QMessageBox *msgbox : msgBoxes) {
		if (msgbox->isVisible())
			visMsgBoxes.append(msgbox);
	}
}

3898 3899
void OBSBasic::ClearSceneData()
{
J
jp9000 已提交
3900 3901
	disableSaving++;

3902 3903 3904 3905
	CloseDialogs();

	ClearVolumeControls();
	ClearListItems(ui->scenes);
J
jp9000 已提交
3906
	ui->sources->Clear();
3907 3908
	ClearQuickTransitions();
	ui->transitions->clear();
3909

3910 3911 3912 3913 3914 3915 3916
	for (size_t i = 0; i < projectors.size(); i++) {
		if (projectors[i])
			delete projectors[i];
	}

	projectors.clear();

3917 3918 3919 3920 3921 3922
	obs_set_output_source(0, nullptr);
	obs_set_output_source(1, nullptr);
	obs_set_output_source(2, nullptr);
	obs_set_output_source(3, nullptr);
	obs_set_output_source(4, nullptr);
	obs_set_output_source(5, nullptr);
3923 3924 3925
	lastScene = nullptr;
	swapScene = nullptr;
	programScene = nullptr;
3926

J
jp9000 已提交
3927
	auto cb = [](void *unused, obs_source_t *source) {
3928 3929 3930 3931 3932
		obs_source_remove(source);
		UNUSED_PARAMETER(unused);
		return true;
	};

3933
	obs_enum_scenes(cb, nullptr);
3934 3935
	obs_enum_sources(cb, nullptr);

3936 3937 3938
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);

J
jp9000 已提交
3939
	disableSaving--;
3940 3941 3942

	blog(LOG_INFO, "All scene data cleared");
	blog(LOG_INFO, "------------------------------------------------");
3943 3944
}

J
jp9000 已提交
3945
void OBSBasic::closeEvent(QCloseEvent *event)
J
jp9000 已提交
3946
{
3947 3948 3949 3950 3951 3952 3953 3954 3955
	/* Do not close window if inside of a temporary event loop because we
	 * could be inside of an Auth::LoadUI call.  Keep trying once per
	 * second until we've exit any known sub-loops. */
	if (os_atomic_load_long(&insideEventLoop) != 0) {
		QTimer::singleShot(1000, this, SLOT(close()));
		event->ignore();
		return;
	}

3956
	if (isVisible())
J
jp9000 已提交
3957 3958 3959
		config_set_string(App()->GlobalConfig(), "BasicWindow",
				  "geometry",
				  saveGeometry().toBase64().constData());
3960

3961
	if (outputHandler && outputHandler->Active()) {
C
cg2121 已提交
3962 3963
		SetShowing(true);

3964
		QMessageBox::StandardButton button = OBSMessageBox::question(
J
jp9000 已提交
3965 3966
			this, QTStr("ConfirmExit.Title"),
			QTStr("ConfirmExit.Text"));
3967 3968 3969

		if (button == QMessageBox::No) {
			event->ignore();
3970
			restart = false;
3971 3972 3973 3974
			return;
		}
	}

3975 3976 3977 3978
	QWidget::closeEvent(event);
	if (!event->isAccepted())
		return;

3979 3980
	blog(LOG_INFO, SHUTDOWN_SEPARATOR);

3981 3982
	closing = true;

J
jp9000 已提交
3983 3984
	if (introCheckThread)
		introCheckThread->wait();
3985 3986
	if (whatsNewInitThread)
		whatsNewInitThread->wait();
3987 3988 3989 3990 3991
	if (updateCheckThread)
		updateCheckThread->wait();
	if (logUploadThread)
		logUploadThread->wait();

P
Palana 已提交
3992 3993
	signalHandlers.clear();

J
jp9000 已提交
3994
	Auth::Save();
J
jp9000 已提交
3995
	SaveProjectNow();
J
jp9000 已提交
3996 3997
	auth.reset();

3998 3999
	delete extraBrowsers;

J
jp9000 已提交
4000 4001
	config_set_string(App()->GlobalConfig(), "BasicWindow", "DockState",
			  saveState().toBase64().constData());
J
jp9000 已提交
4002

4003 4004 4005 4006 4007
#ifdef BROWSER_AVAILABLE
	SaveExtraBrowserDocks();
	ClearExtraBrowserDocks();
#endif

J
jp9000 已提交
4008 4009 4010
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_EXIT);

J
jp9000 已提交
4011
	disableSaving++;
J
jp9000 已提交
4012

4013 4014 4015
	/* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
	 * sources, etc) so that all references are released before shutdown */
	ClearSceneData();
4016 4017

	App()->quit();
4018 4019
}

J
jp9000 已提交
4020
void OBSBasic::changeEvent(QEvent *event)
4021
{
4022 4023 4024 4025 4026 4027 4028 4029 4030
	if (event->type() == QEvent::WindowStateChange) {
		QWindowStateChangeEvent *stateEvent =
			(QWindowStateChangeEvent *)event;

		if (isMinimized()) {
			if (trayIcon && trayIcon->isVisible() &&
			    sysTrayMinimizeToTray()) {
				ToggleShowHide();
			}
4031

4032 4033
			if (previewEnabled)
				EnablePreviewDisplay(false);
4034
		} else if (stateEvent->oldState() & Qt::WindowMinimized &&
4035 4036 4037 4038
			   isVisible()) {
			if (previewEnabled)
				EnablePreviewDisplay(true);
		}
4039
	}
4040 4041
}

4042 4043
void OBSBasic::on_actionShow_Recordings_triggered()
{
4044
	const char *mode = config_get_string(basicConfig, "Output", "Mode");
P
pkviet 已提交
4045
	const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
J
jp9000 已提交
4046 4047 4048 4049 4050 4051 4052 4053 4054 4055
	const char *adv_path =
		strcmp(type, "Standard")
			? config_get_string(basicConfig, "AdvOut", "FFFilePath")
			: config_get_string(basicConfig, "AdvOut",
					    "RecFilePath");
	const char *path = strcmp(mode, "Advanced")
				   ? config_get_string(basicConfig,
						       "SimpleOutput",
						       "FilePath")
				   : adv_path;
4056 4057 4058
	QDesktopServices::openUrl(QUrl::fromLocalFile(path));
}

P
Palana 已提交
4059 4060
void OBSBasic::on_actionRemux_triggered()
{
4061 4062 4063 4064 4065 4066
	if (!remux.isNull()) {
		remux->show();
		remux->raise();
		return;
	}

4067
	const char *mode = config_get_string(basicConfig, "Output", "Mode");
J
jp9000 已提交
4068 4069 4070 4071 4072 4073
	const char *path = strcmp(mode, "Advanced")
				   ? config_get_string(basicConfig,
						       "SimpleOutput",
						       "FilePath")
				   : config_get_string(basicConfig, "AdvOut",
						       "RecFilePath");
4074 4075 4076 4077 4078

	OBSRemux *remuxDlg;
	remuxDlg = new OBSRemux(path, this);
	remuxDlg->show();
	remux = remuxDlg;
P
Palana 已提交
4079 4080
}

P
Palana 已提交
4081 4082
void OBSBasic::on_action_Settings_triggered()
{
4083 4084 4085 4086 4087 4088 4089
	static bool settings_already_executing = false;

	/* Do not load settings window if inside of a temporary event loop
	 * because we could be inside of an Auth::LoadUI call.  Keep trying
	 * once per second until we've exit any known sub-loops. */
	if (os_atomic_load_long(&insideEventLoop) != 0) {
		QTimer::singleShot(1000, this,
J
jp9000 已提交
4090
				   SLOT(on_action_Settings_triggered()));
4091 4092 4093 4094 4095 4096 4097 4098 4099
		return;
	}

	if (settings_already_executing) {
		return;
	}

	settings_already_executing = true;

4100 4101 4102 4103 4104
	{
		OBSBasicSettings settings(this);
		settings.exec();
	}

C
cg2121 已提交
4105
	SystemTray(false);
4106 4107

	settings_already_executing = false;
4108 4109 4110 4111 4112 4113 4114 4115 4116 4117

	if (restart) {
		QMessageBox::StandardButton button = OBSMessageBox::question(
			this, QTStr("Restart"), QTStr("NeedsRestart"));

		if (button == QMessageBox::Yes)
			close();
		else
			restart = false;
	}
P
Palana 已提交
4118 4119
}

J
jp9000 已提交
4120 4121
void OBSBasic::on_actionAdvAudioProperties_triggered()
{
4122 4123 4124 4125 4126
	if (advAudioWindow != nullptr) {
		advAudioWindow->raise();
		return;
	}

4127 4128 4129
	bool iconsVisible = config_get_bool(App()->GlobalConfig(),
					    "BasicWindow", "ShowSourceIcons");

J
jp9000 已提交
4130 4131 4132
	advAudioWindow = new OBSBasicAdvAudio(this);
	advAudioWindow->show();
	advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
4133
	advAudioWindow->SetIconsVisible(iconsVisible);
4134

J
jp9000 已提交
4135 4136
	connect(advAudioWindow, SIGNAL(destroyed()), this,
		SLOT(on_advAudioProps_destroyed()));
J
jp9000 已提交
4137 4138
}

4139 4140 4141 4142 4143
void OBSBasic::on_advAudioProps_clicked()
{
	on_actionAdvAudioProperties_triggered();
}

4144 4145 4146 4147 4148
void OBSBasic::on_advAudioProps_destroyed()
{
	advAudioWindow = nullptr;
}

4149
void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
J
jp9000 已提交
4150
					    QListWidgetItem *prev)
4151
{
4152
	obs_source_t *source = NULL;
J
jp9000 已提交
4153

4154 4155 4156 4157
	if (sceneChanging)
		return;

	if (current) {
4158
		obs_scene_t *scene;
J
jp9000 已提交
4159

P
Palana 已提交
4160
		scene = GetOBSRef<OBSScene>(current);
4161
		source = obs_scene_get_source(scene);
4162 4163
	}

4164
	SetCurrentScene(source);
4165

4166 4167 4168
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);

4169
	UNUSED_PARAMETER(prev);
4170 4171
}

J
jp9000 已提交
4172 4173
void OBSBasic::EditSceneName()
{
4174
	QListWidgetItem *item = ui->scenes->currentItem();
J
jp9000 已提交
4175
	Qt::ItemFlags flags = item->flags();
4176 4177 4178 4179

	item->setFlags(flags | Qt::ItemIsEditable);
	ui->scenes->editItem(item);
	item->setFlags(flags);
J
jp9000 已提交
4180 4181
}

4182 4183
void OBSBasic::AddProjectorMenuMonitors(QMenu *parent, QObject *target,
					const char *slot)
J
jp9000 已提交
4184 4185
{
	QAction *action;
J
jp9000 已提交
4186
	QList<QScreen *> screens = QGuiApplication::screens();
4187
	for (int i = 0; i < screens.size(); i++) {
4188 4189 4190 4191
		QScreen *screen = screens[i];
		QRect screenGeometry = screen->geometry();
		QString name = "";
#ifdef _WIN32
4192 4193 4194 4195 4196
		QTextStream fullname(&name);
		fullname << GetMonitorName(screen->name());
		fullname << " (";
		fullname << (i + 1);
		fullname << ")";
4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211
#elif defined(__APPLE__)
		name = screen->name();
#elif QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)
		name = screen->model().simplified();

		if (name.length() > 1 && name.endsWith("-"))
			name.chop(1);
#endif
		name = name.simplified();

		if (name.length() == 0) {
			name = QString("%1 %2")
				       .arg(QTStr("Display"))
				       .arg(QString::number(i + 1));
		}
J
jp9000 已提交
4212
		QString str =
4213 4214
			QString("%1: %2x%3 @ %4,%5")
				.arg(name,
J
jp9000 已提交
4215 4216 4217 4218
				     QString::number(screenGeometry.width()),
				     QString::number(screenGeometry.height()),
				     QString::number(screenGeometry.x()),
				     QString::number(screenGeometry.y()));
J
jp9000 已提交
4219 4220 4221 4222 4223 4224

		action = parent->addAction(str, target, slot);
		action->setProperty("monitor", i);
	}
}

J
jp9000 已提交
4225
void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
4226
{
J
jp9000 已提交
4227 4228
	QListWidgetItem *item = ui->scenes->itemAt(pos);

4229
	QMenu popup(this);
J
jp9000 已提交
4230
	QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
V
VodBox 已提交
4231

J
jp9000 已提交
4232 4233
	popup.addAction(QTStr("Add"), this,
			SLOT(on_actionAddScene_triggered()));
J
jp9000 已提交
4234

P
Palana 已提交
4235
	if (item) {
J
jp9000 已提交
4236 4237
		QAction *pasteFilters =
			new QAction(QTStr("Paste.Filters"), this);
4238 4239
		pasteFilters->setEnabled(copyFiltersString);
		connect(pasteFilters, SIGNAL(triggered()), this,
J
jp9000 已提交
4240
			SLOT(ScenePasteFilters()));
4241

P
Palana 已提交
4242
		popup.addSeparator();
J
jp9000 已提交
4243 4244 4245 4246
		popup.addAction(QTStr("Duplicate"), this,
				SLOT(DuplicateSelectedScene()));
		popup.addAction(QTStr("Copy.Filters"), this,
				SLOT(SceneCopyFilters()));
4247 4248
		popup.addAction(pasteFilters);
		popup.addSeparator();
J
jp9000 已提交
4249 4250 4251
		popup.addAction(QTStr("Rename"), this, SLOT(EditSceneName()));
		popup.addAction(QTStr("Remove"), this,
				SLOT(RemoveSelectedScene()));
J
jp9000 已提交
4252
		popup.addSeparator();
J
jp9000 已提交
4253

J
jp9000 已提交
4254 4255
		order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
				SLOT(on_actionSceneUp_triggered()));
J
jp9000 已提交
4256 4257 4258 4259 4260 4261 4262 4263 4264 4265
		order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"),
				this, SLOT(on_actionSceneDown_triggered()));
		order.addSeparator();
		order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"),
				this, SLOT(MoveSceneToTop()));
		order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"),
				this, SLOT(MoveSceneToBottom()));
		popup.addMenu(&order);

		popup.addSeparator();
S
Shaolin 已提交
4266

4267 4268
		delete sceneProjectorMenu;
		sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
J
jp9000 已提交
4269
		AddProjectorMenuMonitors(sceneProjectorMenu, this,
J
jp9000 已提交
4270
					 SLOT(OpenSceneProjector()));
J
jp9000 已提交
4271
		popup.addMenu(sceneProjectorMenu);
C
cg2121 已提交
4272 4273

		QAction *sceneWindow = popup.addAction(
J
jp9000 已提交
4274
			QTStr("SceneWindow"), this, SLOT(OpenSceneWindow()));
C
cg2121 已提交
4275 4276

		popup.addAction(sceneWindow);
J
jp9000 已提交
4277
		popup.addSeparator();
J
jp9000 已提交
4278 4279
		popup.addAction(QTStr("Filters"), this,
				SLOT(OpenSceneFilters()));
4280 4281 4282

		popup.addSeparator();

4283 4284
		delete perSceneTransitionMenu;
		perSceneTransitionMenu = CreatePerSceneTransitionMenu();
P
pkv 已提交
4285
		popup.addMenu(perSceneTransitionMenu);
S
Shaolin 已提交
4286 4287 4288

		/* ---------------------- */

J
jp9000 已提交
4289 4290
		QAction *multiviewAction =
			popup.addAction(QTStr("ShowInMultiview"));
S
Shaolin 已提交
4291

J
jp9000 已提交
4292 4293 4294
		OBSSource source = GetCurrentSceneSource();
		OBSData data = obs_source_get_private_settings(source);
		obs_data_release(data);
S
Shaolin 已提交
4295

J
jp9000 已提交
4296
		obs_data_set_default_bool(data, "show_in_multiview", true);
J
jp9000 已提交
4297
		bool show = obs_data_get_bool(data, "show_in_multiview");
S
Shaolin 已提交
4298

J
jp9000 已提交
4299 4300
		multiviewAction->setCheckable(true);
		multiviewAction->setChecked(show);
S
Shaolin 已提交
4301

J
jp9000 已提交
4302 4303 4304 4305
		auto showInMultiview = [](OBSData data) {
			bool show =
				obs_data_get_bool(data, "show_in_multiview");
			obs_data_set_bool(data, "show_in_multiview", !show);
J
jp9000 已提交
4306 4307 4308 4309
			OBSProjector::UpdateMultiviewProjectors();
		};

		connect(multiviewAction, &QAction::triggered,
J
jp9000 已提交
4310
			std::bind(showInMultiview, data));
P
Palana 已提交
4311
	}
J
jp9000 已提交
4312

V
VodBox 已提交
4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323
	popup.addSeparator();

	bool grid = ui->scenes->GetGridMode();

	QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode")
					       : QTStr("Basic.Main.GridMode"),
					  this);
	connect(gridAction, SIGNAL(triggered()), this,
		SLOT(on_actionGridMode_triggered()));
	popup.addAction(gridAction);

J
jp9000 已提交
4324
	popup.exec(QCursor::pos());
4325 4326
}

V
VodBox 已提交
4327 4328 4329 4330 4331 4332
void OBSBasic::on_actionGridMode_triggered()
{
	bool gridMode = !ui->scenes->GetGridMode();
	ui->scenes->SetGridMode(gridMode);
}

J
jp9000 已提交
4333
void OBSBasic::on_actionAddScene_triggered()
4334
{
4335
	string name;
S
Socapex 已提交
4336
	QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
P
Palana 已提交
4337

4338
	int i = 2;
P
Palana 已提交
4339
	QString placeHolderText = format.arg(i);
4340
	obs_source_t *source = nullptr;
P
Palana 已提交
4341 4342
	while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
		obs_source_release(source);
P
Palana 已提交
4343
		placeHolderText = format.arg(++i);
P
Palana 已提交
4344
	}
S
Socapex 已提交
4345

J
jp9000 已提交
4346 4347 4348
	bool accepted = NameDialog::AskForName(
		this, QTStr("Basic.Main.AddSceneDlg.Title"),
		QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
4349

J
jp9000 已提交
4350
	if (accepted) {
J
jp9000 已提交
4351
		if (name.empty()) {
4352
			OBSMessageBox::warning(this,
J
jp9000 已提交
4353 4354
					       QTStr("NoNameEntered.Title"),
					       QTStr("NoNameEntered.Text"));
J
jp9000 已提交
4355 4356 4357 4358
			on_actionAddScene_triggered();
			return;
		}

4359
		obs_source_t *source = obs_get_source_by_name(name.c_str());
4360
		if (source) {
J
jp9000 已提交
4361 4362
			OBSMessageBox::warning(this, QTStr("NameExists.Title"),
					       QTStr("NameExists.Text"));
4363 4364

			obs_source_release(source);
J
jp9000 已提交
4365
			on_actionAddScene_triggered();
4366 4367 4368
			return;
		}

4369
		obs_scene_t *scene = obs_scene_create(name.c_str());
4370
		source = obs_scene_get_source(scene);
4371
		SetCurrentScene(source);
4372
		obs_scene_release(scene);
4373
	}
4374 4375
}

J
jp9000 已提交
4376
void OBSBasic::on_actionRemoveScene_triggered()
4377
{
J
jp9000 已提交
4378
	OBSScene scene = GetCurrentScene();
4379
	obs_source_t *source = obs_scene_get_source(scene);
4380 4381 4382

	if (source && QueryRemoveSource(source))
		obs_source_remove(source);
4383 4384
}

J
jp9000 已提交
4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402
void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx)
{
	int idx = ui->scenes->currentRow();
	if (idx == -1 || idx == invalidIdx)
		return;

	sceneChanging = true;

	QListWidgetItem *item = ui->scenes->takeItem(idx);

	if (!relative)
		idx = 0;

	ui->scenes->insertItem(idx + offset, item);
	ui->scenes->setCurrentRow(idx + offset);
	item->setSelected(true);

	sceneChanging = false;
4403 4404

	OBSProjector::UpdateMultiviewProjectors();
J
jp9000 已提交
4405 4406
}

J
jp9000 已提交
4407
void OBSBasic::on_actionSceneUp_triggered()
4408
{
J
jp9000 已提交
4409
	ChangeSceneIndex(true, -1, 0);
4410 4411
}

J
jp9000 已提交
4412
void OBSBasic::on_actionSceneDown_triggered()
4413
{
J
jp9000 已提交
4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424
	ChangeSceneIndex(true, 1, ui->scenes->count() - 1);
}

void OBSBasic::MoveSceneToTop()
{
	ChangeSceneIndex(false, 0, 0);
}

void OBSBasic::MoveSceneToBottom()
{
	ChangeSceneIndex(false, ui->scenes->count() - 1,
J
jp9000 已提交
4425
			 ui->scenes->count() - 1);
4426 4427
}

J
jp9000 已提交
4428 4429
void OBSBasic::EditSceneItemName()
{
J
jp9000 已提交
4430 4431
	int idx = GetTopSelectedSourceItem();
	ui->sources->Edit(idx);
J
jp9000 已提交
4432 4433
}

J
jp9000 已提交
4434 4435
void OBSBasic::SetDeinterlacingMode()
{
J
jp9000 已提交
4436
	QAction *action = reinterpret_cast<QAction *>(sender());
J
jp9000 已提交
4437 4438 4439 4440 4441 4442 4443 4444 4445 4446
	obs_deinterlace_mode mode =
		(obs_deinterlace_mode)action->property("mode").toInt();
	OBSSceneItem sceneItem = GetCurrentSceneItem();
	obs_source_t *source = obs_sceneitem_get_source(sceneItem);

	obs_source_set_deinterlace_mode(source, mode);
}

void OBSBasic::SetDeinterlacingOrder()
{
J
jp9000 已提交
4447
	QAction *action = reinterpret_cast<QAction *>(sender());
J
jp9000 已提交
4448 4449 4450 4451 4452 4453 4454 4455
	obs_deinterlace_field_order order =
		(obs_deinterlace_field_order)action->property("order").toInt();
	OBSSceneItem sceneItem = GetCurrentSceneItem();
	obs_source_t *source = obs_sceneitem_get_source(sceneItem);

	obs_source_set_deinterlace_field_order(source, order);
}

P
pkv 已提交
4456
QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
J
jp9000 已提交
4457 4458 4459 4460 4461 4462 4463
{
	obs_deinterlace_mode deinterlaceMode =
		obs_source_get_deinterlace_mode(source);
	obs_deinterlace_field_order deinterlaceOrder =
		obs_source_get_deinterlace_field_order(source);
	QAction *action;

J
jp9000 已提交
4464 4465 4466 4467 4468
#define ADD_MODE(name, mode)                                    \
	action = menu->addAction(QTStr("" name), this,          \
				 SLOT(SetDeinterlacingMode())); \
	action->setProperty("mode", (int)mode);                 \
	action->setCheckable(true);                             \
J
jp9000 已提交
4469 4470
	action->setChecked(deinterlaceMode == mode);

J
jp9000 已提交
4471 4472 4473 4474 4475 4476
	ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE);
	ADD_MODE("Deinterlacing.Discard", OBS_DEINTERLACE_MODE_DISCARD);
	ADD_MODE("Deinterlacing.Retro", OBS_DEINTERLACE_MODE_RETRO);
	ADD_MODE("Deinterlacing.Blend", OBS_DEINTERLACE_MODE_BLEND);
	ADD_MODE("Deinterlacing.Blend2x", OBS_DEINTERLACE_MODE_BLEND_2X);
	ADD_MODE("Deinterlacing.Linear", OBS_DEINTERLACE_MODE_LINEAR);
J
jp9000 已提交
4477
	ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
J
jp9000 已提交
4478 4479
	ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
	ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
J
jp9000 已提交
4480 4481 4482 4483
#undef ADD_MODE

	menu->addSeparator();

J
jp9000 已提交
4484
#define ADD_ORDER(name, order)                                       \
J
jp9000 已提交
4485
	action = menu->addAction(QTStr("Deinterlacing." name), this, \
J
jp9000 已提交
4486 4487 4488
				 SLOT(SetDeinterlacingOrder()));     \
	action->setProperty("order", (int)order);                    \
	action->setCheckable(true);                                  \
J
jp9000 已提交
4489 4490
	action->setChecked(deinterlaceOrder == order);

J
jp9000 已提交
4491
	ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
J
jp9000 已提交
4492 4493 4494 4495 4496 4497
	ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
#undef ADD_ORDER

	return menu;
}

4498 4499
void OBSBasic::SetScaleFilter()
{
J
jp9000 已提交
4500
	QAction *action = reinterpret_cast<QAction *>(sender());
4501 4502 4503 4504 4505 4506
	obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
	OBSSceneItem sceneItem = GetCurrentSceneItem();

	obs_sceneitem_set_scale_filter(sceneItem, mode);
}

P
pkv 已提交
4507
QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
4508 4509 4510 4511
{
	obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
	QAction *action;

J
jp9000 已提交
4512 4513 4514 4515 4516
#define ADD_MODE(name, mode)                                                   \
	action =                                                               \
		menu->addAction(QTStr("" name), this, SLOT(SetScaleFilter())); \
	action->setProperty("mode", (int)mode);                                \
	action->setCheckable(true);                                            \
4517 4518
	action->setChecked(scaleFilter == mode);

J
jp9000 已提交
4519 4520
	ADD_MODE("Disable", OBS_SCALE_DISABLE);
	ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
4521
	ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
J
jp9000 已提交
4522 4523 4524
	ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
	ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
	ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
4525 4526 4527 4528 4529
#undef ADD_MODE

	return menu;
}

J
jp9000 已提交
4530 4531 4532 4533
QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
					QWidgetAction *widgetAction,
					ColorSelect *select,
					obs_sceneitem_t *item)
4534 4535 4536 4537
{
	QAction *action;

	menu->setStyleSheet(QString(
J
jp9000 已提交
4538 4539 4540 4541 4542 4543 4544
		"*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}"
		"*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}"
		"*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}"
		"*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}"
		"*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}"
		"*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}"
		"*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}"
4545 4546 4547 4548 4549 4550 4551 4552
		"*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}"));

	obs_data_t *privData = obs_sceneitem_get_private_settings(item);
	obs_data_release(privData);

	obs_data_set_default_int(privData, "color-preset", 0);
	int preset = obs_data_get_int(privData, "color-preset");

J
jp9000 已提交
4553
	action = menu->addAction(QTStr("Clear"), this, +SLOT(ColorChange()));
4554 4555 4556 4557 4558
	action->setCheckable(true);
	action->setProperty("bgColor", 0);
	action->setChecked(preset == 0);

	action = menu->addAction(QTStr("CustomColor"), this,
J
jp9000 已提交
4559
				 +SLOT(ColorChange()));
4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570
	action->setCheckable(true);
	action->setProperty("bgColor", 1);
	action->setChecked(preset == 1);

	menu->addSeparator();

	widgetAction->setDefaultWidget(select);

	for (int i = 1; i < 9; i++) {
		stringstream button;
		button << "preset" << i;
J
jp9000 已提交
4571 4572
		QPushButton *colorButton =
			select->findChild<QPushButton *>(button.str().c_str());
4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585
		if (preset == i + 1)
			colorButton->setStyleSheet("border: 2px solid black");

		colorButton->setProperty("bgColor", i);
		select->connect(colorButton, SIGNAL(released()), this,
				SLOT(ColorChange()));
	}

	menu->addAction(widgetAction);

	return menu;
}

P
pkv 已提交
4586
ColorSelect::ColorSelect(QWidget *parent)
J
jp9000 已提交
4587
	: QWidget(parent), ui(new Ui::ColorSelect)
P
pkv 已提交
4588 4589 4590 4591
{
	ui->setupUi(this);
}

J
jp9000 已提交
4592
void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
4593
{
4594
	QMenu popup(this);
4595 4596 4597 4598 4599 4600 4601
	delete previewProjectorSource;
	delete sourceProjector;
	delete scaleFilteringMenu;
	delete colorMenu;
	delete colorWidgetAction;
	delete colorSelect;
	delete deinterlaceMenu;
J
jp9000 已提交
4602 4603 4604

	if (preview) {
		QAction *action = popup.addAction(
J
jp9000 已提交
4605 4606
			QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
			SLOT(TogglePreview()));
J
jp9000 已提交
4607
		action->setCheckable(true);
4608
		action->setChecked(
J
jp9000 已提交
4609
			obs_display_enabled(ui->preview->GetDisplay()));
4610 4611
		if (IsPreviewProgramMode())
			action->setEnabled(false);
J
jp9000 已提交
4612

J
Joseph El-Khouri 已提交
4613 4614
		popup.addAction(ui->actionLockPreview);
		popup.addMenu(ui->scalingMenu);
J
jp9000 已提交
4615

4616
		previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
P
pkv 已提交
4617
		AddProjectorMenuMonitors(previewProjectorSource, this,
J
jp9000 已提交
4618
					 SLOT(OpenPreviewProjector()));
J
jp9000 已提交
4619

P
pkv 已提交
4620
		popup.addMenu(previewProjectorSource);
J
jp9000 已提交
4621

J
jp9000 已提交
4622 4623 4624
		QAction *previewWindow =
			popup.addAction(QTStr("PreviewWindow"), this,
					SLOT(OpenPreviewWindow()));
C
cg2121 已提交
4625 4626 4627

		popup.addAction(previewWindow);

J
jp9000 已提交
4628 4629 4630
		popup.addSeparator();
	}

J
jp9000 已提交
4631 4632 4633 4634
	QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
	if (addSourceMenu)
		popup.addMenu(addSourceMenu);

4635
	ui->actionCopyFilters->setEnabled(false);
4636
	ui->actionCopySource->setEnabled(false);
4637

J
jp9000 已提交
4638 4639
	if (ui->sources->MultipleBaseSelected()) {
		popup.addSeparator();
J
jp9000 已提交
4640 4641
		popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
				SLOT(GroupSelectedItems()));
J
jp9000 已提交
4642 4643 4644

	} else if (ui->sources->GroupsSelected()) {
		popup.addSeparator();
J
jp9000 已提交
4645 4646
		popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
				SLOT(UngroupSelectedGroups()));
J
jp9000 已提交
4647 4648
	}

4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659
	popup.addSeparator();
	popup.addAction(ui->actionCopySource);
	popup.addAction(ui->actionPasteRef);
	popup.addAction(ui->actionPasteDup);
	popup.addSeparator();

	popup.addSeparator();
	popup.addAction(ui->actionCopyFilters);
	popup.addAction(ui->actionPasteFilters);
	popup.addSeparator();

J
jp9000 已提交
4660
	if (idx != -1) {
J
jp9000 已提交
4661 4662 4663
		if (addSourceMenu)
			popup.addSeparator();

J
jp9000 已提交
4664
		OBSSceneItem sceneItem = ui->sources->Get(idx);
4665
		bool lock = obs_sceneitem_locked(sceneItem);
4666
		obs_source_t *source = obs_sceneitem_get_source(sceneItem);
J
jp9000 已提交
4667 4668
		uint32_t flags = obs_source_get_output_flags(source);
		bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
J
jp9000 已提交
4669 4670
				    OBS_SOURCE_ASYNC_VIDEO;
		bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
J
John Bradley 已提交
4671 4672
		QAction *action;

4673 4674 4675
		colorMenu = new QMenu(QTStr("ChangeBG"));
		colorWidgetAction = new QWidgetAction(colorMenu);
		colorSelect = new ColorSelect(colorMenu);
J
jp9000 已提交
4676 4677
		popup.addMenu(AddBackgroundColorMenu(
			colorMenu, colorWidgetAction, colorSelect, sceneItem));
J
jp9000 已提交
4678 4679
		popup.addAction(QTStr("Rename"), this,
				SLOT(EditSceneItemName()));
4680
		popup.addAction(QTStr("Remove"), this,
4681
				SLOT(on_actionRemoveSource_triggered()));
J
jp9000 已提交
4682 4683
		popup.addSeparator();
		popup.addMenu(ui->orderMenu);
J
jp9000 已提交
4684
		popup.addMenu(ui->transformMenu);
J
jp9000 已提交
4685

4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697
		ui->actionResetTransform->setEnabled(!lock);
		ui->actionRotate90CW->setEnabled(!lock);
		ui->actionRotate90CCW->setEnabled(!lock);
		ui->actionRotate180->setEnabled(!lock);
		ui->actionFlipHorizontal->setEnabled(!lock);
		ui->actionFlipVertical->setEnabled(!lock);
		ui->actionFitToScreen->setEnabled(!lock);
		ui->actionStretchToScreen->setEnabled(!lock);
		ui->actionCenterToScreen->setEnabled(!lock);
		ui->actionVerticalCenter->setEnabled(!lock);
		ui->actionHorizontalCenter->setEnabled(!lock);

4698
		sourceProjector = new QMenu(QTStr("SourceProjector"));
J
jp9000 已提交
4699
		AddProjectorMenuMonitors(sourceProjector, this,
J
jp9000 已提交
4700
					 SLOT(OpenSourceProjector()));
J
jp9000 已提交
4701

C
cg2121 已提交
4702
		QAction *sourceWindow = popup.addAction(
J
jp9000 已提交
4703
			QTStr("SourceWindow"), this, SLOT(OpenSourceWindow()));
C
cg2121 已提交
4704 4705 4706

		popup.addAction(sourceWindow);

J
jp9000 已提交
4707
		popup.addSeparator();
4708 4709

		if (hasAudio) {
J
jp9000 已提交
4710 4711 4712
			QAction *actionHideMixer =
				popup.addAction(QTStr("HideMixer"), this,
						SLOT(ToggleHideMixer()));
4713 4714 4715 4716
			actionHideMixer->setCheckable(true);
			actionHideMixer->setChecked(SourceMixerHidden(source));
		}

J
jp9000 已提交
4717
		if (isAsyncVideo) {
4718
			deinterlaceMenu = new QMenu(QTStr("Deinterlacing"));
J
jp9000 已提交
4719 4720
			popup.addMenu(
				AddDeinterlacingMenu(deinterlaceMenu, source));
J
jp9000 已提交
4721 4722
			popup.addSeparator();
		}
4723

J
jp9000 已提交
4724 4725 4726
		QAction *resizeOutput =
			popup.addAction(QTStr("ResizeOutputSizeOfSource"), this,
					SLOT(ResizeOutputSizeOfSource()));
4727 4728 4729 4730

		int width = obs_source_get_width(source);
		int height = obs_source_get_height(source);

4731
		resizeOutput->setEnabled(!obs_video_active());
4732

4733
		if (width < 8 || height < 8)
4734 4735
			resizeOutput->setEnabled(false);

4736
		scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
J
jp9000 已提交
4737 4738
		popup.addMenu(
			AddScaleFilteringMenu(scaleFilteringMenu, sceneItem));
4739 4740
		popup.addSeparator();

J
jp9000 已提交
4741
		popup.addMenu(sourceProjector);
C
cg2121 已提交
4742
		popup.addAction(sourceWindow);
J
jp9000 已提交
4743
		popup.addSeparator();
J
John Bradley 已提交
4744 4745

		action = popup.addAction(QTStr("Interact"), this,
J
jp9000 已提交
4746
					 SLOT(on_actionInteract_triggered()));
J
John Bradley 已提交
4747 4748

		action->setEnabled(obs_source_get_output_flags(source) &
J
jp9000 已提交
4749
				   OBS_SOURCE_INTERACTION);
J
John Bradley 已提交
4750

J
jp9000 已提交
4751
		popup.addAction(QTStr("Filters"), this, SLOT(OpenFilters()));
J
jp9000 已提交
4752 4753
		popup.addAction(QTStr("Properties"), this,
				SLOT(on_actionSourceProperties_triggered()));
4754 4755

		ui->actionCopyFilters->setEnabled(true);
4756
		ui->actionCopySource->setEnabled(true);
4757 4758
	} else {
		ui->actionPasteFilters->setEnabled(false);
J
jp9000 已提交
4759 4760 4761
	}

	popup.exec(QCursor::pos());
4762 4763
}

J
jp9000 已提交
4764 4765
void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
{
J
jp9000 已提交
4766 4767 4768 4769
	if (ui->scenes->count()) {
		QModelIndex idx = ui->sources->indexAt(pos);
		CreateSourcePopupMenu(idx.row(), false);
	}
P
Palana 已提交
4770 4771
}

4772 4773 4774 4775 4776 4777
void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
{
	if (!witem)
		return;

	if (IsPreviewProgramMode()) {
J
jp9000 已提交
4778 4779 4780
		bool doubleClickSwitch =
			config_get_bool(App()->GlobalConfig(), "BasicWindow",
					"TransitionOnDoubleClick");
4781

4782 4783
		if (doubleClickSwitch)
			TransitionClicked();
4784 4785 4786
	}
}

J
jp9000 已提交
4787
void OBSBasic::AddSource(const char *id)
4788
{
4789 4790 4791
	if (id && *id) {
		OBSBasicSourceSelect sourceSelect(this, id);
		sourceSelect.exec();
4792
		if (sourceSelect.newSource && strcmp(id, "group") != 0)
4793
			CreatePropertiesWindow(sourceSelect.newSource);
4794
	}
4795 4796
}

4797
QMenu *OBSBasic::CreateAddSourcePopupMenu()
4798
{
4799
	const char *unversioned_type;
4800
	const char *type;
J
jp9000 已提交
4801
	bool foundValues = false;
4802
	bool foundDeprecated = false;
J
jp9000 已提交
4803
	size_t idx = 0;
4804

4805
	QMenu *popup = new QMenu(QTStr("Add"), this);
4806
	QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
4807

J
jp9000 已提交
4808 4809
	auto getActionAfter = [](QMenu *menu, const QString &name) {
		QList<QAction *> actions = menu->actions();
J
jp9000 已提交
4810 4811 4812 4813 4814 4815

		for (QAction *menuAction : actions) {
			if (menuAction->text().compare(name) >= 0)
				return menuAction;
		}

J
jp9000 已提交
4816
		return (QAction *)nullptr;
J
jp9000 已提交
4817 4818
	};

J
jp9000 已提交
4819 4820
	auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
						const char *name) {
J
jp9000 已提交
4821 4822
		QString qname = QT_UTF8(name);
		QAction *popupItem = new QAction(qname, this);
J
jp9000 已提交
4823
		popupItem->setData(QT_UTF8(type));
J
jp9000 已提交
4824 4825
		connect(popupItem, SIGNAL(triggered(bool)), this,
			SLOT(AddSourceFromAction()));
J
jp9000 已提交
4826

C
Clayton Groeneveld 已提交
4827 4828 4829 4830 4831 4832 4833 4834 4835
		QIcon icon;

		if (strcmp(type, "scene") == 0)
			icon = GetSceneIcon();
		else
			icon = GetSourceIcon(type);

		popupItem->setIcon(icon);

J
jp9000 已提交
4836 4837
		QAction *after = getActionAfter(popup, qname);
		popup->insertAction(after, popupItem);
J
jp9000 已提交
4838
	};
4839

4840
	while (obs_enum_input_types2(idx++, &type, &unversioned_type)) {
J
jp9000 已提交
4841
		const char *name = obs_source_get_display_name(type);
4842
		uint32_t caps = obs_get_source_output_flags(type);
J
jp9000 已提交
4843

4844 4845 4846
		if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
			continue;

4847
		if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
4848
			addSource(popup, unversioned_type, name);
4849
		} else {
4850
			addSource(deprecated, unversioned_type, name);
4851
			foundDeprecated = true;
4852
		}
4853
		foundValues = true;
4854 4855
	}

J
jp9000 已提交
4856
	addSource(popup, "scene", Str("Basic.Scene"));
J
jp9000 已提交
4857

J
jp9000 已提交
4858 4859
	popup->addSeparator();
	QAction *addGroup = new QAction(QTStr("Group"), this);
4860
	addGroup->setData(QT_UTF8("group"));
C
Clayton Groeneveld 已提交
4861
	addGroup->setIcon(GetGroupIcon());
J
jp9000 已提交
4862 4863
	connect(addGroup, SIGNAL(triggered(bool)), this,
		SLOT(AddSourceFromAction()));
J
jp9000 已提交
4864 4865
	popup->addAction(addGroup);

4866 4867 4868 4869 4870
	if (!foundDeprecated) {
		delete deprecated;
		deprecated = nullptr;
	}

4871 4872 4873
	if (!foundValues) {
		delete popup;
		popup = nullptr;
4874 4875

	} else if (foundDeprecated) {
J
jp9000 已提交
4876
		popup->addSeparator();
4877
		popup->addMenu(deprecated);
4878
	}
4879 4880 4881 4882 4883 4884

	return popup;
}

void OBSBasic::AddSourceFromAction()
{
J
jp9000 已提交
4885
	QAction *action = qobject_cast<QAction *>(sender());
4886 4887 4888 4889 4890 4891 4892 4893 4894 4895
	if (!action)
		return;

	AddSource(QT_TO_UTF8(action->data().toString()));
}

void OBSBasic::AddSourcePopupMenu(const QPoint &pos)
{
	if (!GetCurrentScene()) {
		// Tell the user he needs a scene first (help beginners).
J
jp9000 已提交
4896 4897 4898
		OBSMessageBox::information(
			this, QTStr("Basic.Main.AddSourceHelp.Title"),
			QTStr("Basic.Main.AddSourceHelp.Text"));
4899 4900 4901
		return;
	}

4902
	QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
4903 4904
	if (popup)
		popup->exec(pos);
4905 4906
}

J
jp9000 已提交
4907
void OBSBasic::on_actionAddSource_triggered()
4908
{
J
jp9000 已提交
4909
	AddSourcePopupMenu(QCursor::pos());
4910 4911
}

J
jp9000 已提交
4912 4913 4914
static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
{
	vector<OBSSceneItem> &items =
J
jp9000 已提交
4915
		*reinterpret_cast<vector<OBSSceneItem> *>(param);
J
jp9000 已提交
4916 4917 4918 4919 4920 4921 4922 4923 4924

	if (obs_sceneitem_selected(item)) {
		items.emplace_back(item);
	} else if (obs_sceneitem_is_group(item)) {
		obs_sceneitem_group_enum_items(item, remove_items, &items);
	}
	return true;
};

J
jp9000 已提交
4925
void OBSBasic::on_actionRemoveSource_triggered()
4926
{
4927
	vector<OBSSceneItem> items;
4928

J
jp9000 已提交
4929
	obs_scene_enum_items(GetCurrentScene(), remove_items, &items);
4930 4931 4932 4933

	if (!items.size())
		return;

J
jp9000 已提交
4934
	auto removeMultiple = [this](size_t count) {
4935
		QString text = QTStr("ConfirmRemove.TextMultiple")
J
jp9000 已提交
4936
				       .arg(QString::number(count));
4937 4938 4939

		QMessageBox remove_items(this);
		remove_items.setText(text);
J
jp9000 已提交
4940 4941
		QAbstractButton *Yes = remove_items.addButton(
			QTStr("Yes"), QMessageBox::YesRole);
4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961
		remove_items.addButton(QTStr("No"), QMessageBox::NoRole);
		remove_items.setIcon(QMessageBox::Question);
		remove_items.setWindowTitle(QTStr("ConfirmRemove.Title"));
		remove_items.exec();

		return Yes == remove_items.clickedButton();
	};

	if (items.size() == 1) {
		OBSSceneItem &item = items[0];
		obs_source_t *source = obs_sceneitem_get_source(item);

		if (source && QueryRemoveSource(source))
			obs_sceneitem_remove(item);
	} else {
		if (removeMultiple(items.size())) {
			for (auto &item : items)
				obs_sceneitem_remove(item);
		}
	}
4962 4963
}

J
John Bradley 已提交
4964 4965 4966 4967 4968 4969 4970 4971 4972
void OBSBasic::on_actionInteract_triggered()
{
	OBSSceneItem item = GetCurrentSceneItem();
	OBSSource source = obs_sceneitem_get_source(item);

	if (source)
		CreateInteractionWindow(source);
}

J
jp9000 已提交
4973
void OBSBasic::on_actionSourceProperties_triggered()
4974
{
4975
	OBSSceneItem item = GetCurrentSceneItem();
J
jp9000 已提交
4976
	OBSSource source = obs_sceneitem_get_source(item);
4977

4978 4979
	if (source)
		CreatePropertiesWindow(source);
4980 4981
}

J
jp9000 已提交
4982
void OBSBasic::on_actionSourceUp_triggered()
4983
{
J
jp9000 已提交
4984
	OBSSceneItem item = GetCurrentSceneItem();
J
jp9000 已提交
4985
	obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
4986
}
J
jp9000 已提交
4987

J
jp9000 已提交
4988
void OBSBasic::on_actionSourceDown_triggered()
4989
{
J
jp9000 已提交
4990
	OBSSceneItem item = GetCurrentSceneItem();
J
jp9000 已提交
4991
	obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
4992 4993
}

J
jp9000 已提交
4994 4995 4996
void OBSBasic::on_actionMoveUp_triggered()
{
	OBSSceneItem item = GetCurrentSceneItem();
J
jp9000 已提交
4997
	obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
J
jp9000 已提交
4998 4999 5000 5001 5002
}

void OBSBasic::on_actionMoveDown_triggered()
{
	OBSSceneItem item = GetCurrentSceneItem();
J
jp9000 已提交
5003
	obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
J
jp9000 已提交
5004 5005 5006 5007 5008
}

void OBSBasic::on_actionMoveToTop_triggered()
{
	OBSSceneItem item = GetCurrentSceneItem();
J
jp9000 已提交
5009
	obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
J
jp9000 已提交
5010 5011 5012 5013 5014
}

void OBSBasic::on_actionMoveToBottom_triggered()
{
	OBSSceneItem item = GetCurrentSceneItem();
J
jp9000 已提交
5015
	obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
J
jp9000 已提交
5016 5017
}

5018
static BPtr<char> ReadLogFile(const char *subdir, const char *log)
J
jp9000 已提交
5019
{
5020
	char logDir[512];
5021
	if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
5022
		return nullptr;
J
jp9000 已提交
5023

J
jpark37 已提交
5024
	string path = logDir;
J
jp9000 已提交
5025 5026 5027
	path += "/";
	path += log;

5028
	BPtr<char> file = os_quick_read_utf8_file(path.c_str());
J
jp9000 已提交
5029 5030 5031 5032 5033 5034
	if (!file)
		blog(LOG_WARNING, "Failed to read log file %s", path.c_str());

	return file;
}

5035
void OBSBasic::UploadLog(const char *subdir, const char *file)
J
jp9000 已提交
5036
{
5037
	BPtr<char> fileString{ReadLogFile(subdir, file)};
J
jp9000 已提交
5038

5039
	if (!fileString)
J
jp9000 已提交
5040 5041
		return;

5042
	if (!*fileString)
J
jp9000 已提交
5043 5044 5045 5046
		return;

	ui->menuLogFiles->setEnabled(false);

5047
	stringstream ss;
J
jp9000 已提交
5048 5049 5050
	ss << "OBS " << App()->GetVersionString() << " log file uploaded at "
	   << CurrentDateTimeString() << "\n\n"
	   << fileString;
F
fryshorts 已提交
5051

5052 5053 5054
	if (logUploadThread) {
		logUploadThread->wait();
	}
F
fryshorts 已提交
5055

J
jp9000 已提交
5056 5057 5058
	RemoteTextThread *thread =
		new RemoteTextThread("https://obsproject.com/logs/upload",
				     "text/plain", ss.str().c_str());
5059

5060
	logUploadThread.reset(thread);
J
jp9000 已提交
5061 5062
	connect(thread, &RemoteTextThread::Result, this,
		&OBSBasic::logUploadFinished);
5063
	logUploadThread->start();
J
jp9000 已提交
5064 5065
}

P
Palana 已提交
5066 5067
void OBSBasic::on_actionShowLogs_triggered()
{
5068
	char logDir[512];
5069
	if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
5070 5071
		return;

P
Palana 已提交
5072 5073 5074 5075
	QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
	QDesktopServices::openUrl(url);
}

J
jp9000 已提交
5076 5077
void OBSBasic::on_actionUploadCurrentLog_triggered()
{
5078
	UploadLog("obs-studio/logs", App()->GetCurrentLog());
J
jp9000 已提交
5079 5080 5081 5082
}

void OBSBasic::on_actionUploadLastLog_triggered()
{
5083
	UploadLog("obs-studio/logs", App()->GetLastLog());
J
jp9000 已提交
5084 5085
}

5086 5087 5088
void OBSBasic::on_actionViewCurrentLog_triggered()
{
	char logDir[512];
5089
	if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
5090 5091
		return;

J
jp9000 已提交
5092
	const char *log = App()->GetCurrentLog();
5093

J
jpark37 已提交
5094
	string path = logDir;
5095 5096 5097 5098 5099 5100 5101
	path += "/";
	path += log;

	QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
	QDesktopServices::openUrl(url);
}

J
jp9000 已提交
5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116
void OBSBasic::on_actionShowCrashLogs_triggered()
{
	char logDir[512];
	if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/crashes") <= 0)
		return;

	QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
	QDesktopServices::openUrl(url);
}

void OBSBasic::on_actionUploadLastCrashLog_triggered()
{
	UploadLog("obs-studio/crashes", App()->GetLastCrashLog());
}

J
jp9000 已提交
5117 5118
void OBSBasic::on_actionCheckForUpdates_triggered()
{
J
jp9000 已提交
5119
	CheckForUpdates(true);
J
jp9000 已提交
5120 5121
}

5122
void OBSBasic::logUploadFinished(const QString &text, const QString &error)
J
jp9000 已提交
5123 5124 5125
{
	ui->menuLogFiles->setEnabled(true);

5126
	if (text.isEmpty()) {
J
jp9000 已提交
5127 5128 5129
		OBSMessageBox::critical(
			this, QTStr("LogReturnDialog.ErrorUploadingLog"),
			error);
J
jp9000 已提交
5130 5131 5132
		return;
	}

5133
	obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
5134
	string resURL = obs_data_get_string(returnData, "url");
5135
	QString logURL = resURL.c_str();
J
jp9000 已提交
5136 5137 5138 5139 5140 5141
	obs_data_release(returnData);

	OBSLogReply logDialog(this, logURL);
	logDialog.exec();
}

J
jp9000 已提交
5142
static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
J
jp9000 已提交
5143
			   obs_source_t *source, const string &name)
5144
{
5145 5146 5147 5148
	const char *prevName = obs_source_get_name(source);
	if (name == prevName)
		return;

J
jp9000 已提交
5149 5150
	obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
	QListWidgetItem *listItem = listWidget->currentItem();
5151

5152
	if (foundSource || name.empty()) {
5153
		listItem->setText(QT_UTF8(prevName));
5154

5155
		if (foundSource) {
5156
			OBSMessageBox::warning(parent,
J
jp9000 已提交
5157 5158
					       QTStr("NameExists.Title"),
					       QTStr("NameExists.Text"));
5159
		} else if (name.empty()) {
5160
			OBSMessageBox::warning(parent,
J
jp9000 已提交
5161 5162
					       QTStr("NoNameEntered.Title"),
					       QTStr("NoNameEntered.Text"));
5163 5164
		}

5165 5166 5167
		obs_source_release(foundSource);
	} else {
		listItem->setText(QT_UTF8(name.c_str()));
5168
		obs_source_set_name(source, name.c_str());
5169 5170 5171
	}
}

J
jp9000 已提交
5172
void OBSBasic::SceneNameEdited(QWidget *editor,
J
jp9000 已提交
5173
			       QAbstractItemDelegate::EndEditHint endHint)
J
jp9000 已提交
5174
{
J
jp9000 已提交
5175 5176 5177
	OBSScene scene = GetCurrentScene();
	QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
	string text = QT_TO_UTF8(edit->text().trimmed());
J
jp9000 已提交
5178 5179 5180 5181

	if (!scene)
		return;

5182
	obs_source_t *source = obs_scene_get_source(scene);
5183
	RenameListItem(this, ui->scenes, source, text);
J
jp9000 已提交
5184

J
jp9000 已提交
5185 5186 5187
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);

J
jp9000 已提交
5188 5189 5190
	UNUSED_PARAMETER(endHint);
}

J
jp9000 已提交
5191 5192 5193 5194 5195 5196 5197 5198
void OBSBasic::OpenFilters()
{
	OBSSceneItem item = GetCurrentSceneItem();
	OBSSource source = obs_sceneitem_get_source(item);

	CreateFiltersWindow(source);
}

J
jp9000 已提交
5199 5200 5201 5202 5203 5204 5205 5206
void OBSBasic::OpenSceneFilters()
{
	OBSScene scene = GetCurrentScene();
	OBSSource source = obs_scene_get_source(scene);

	CreateFiltersWindow(source);
}

J
jp9000 已提交
5207 5208 5209 5210
#define RECORDING_START \
	"==== Recording Start ==============================================="
#define RECORDING_STOP \
	"==== Recording Stop ================================================"
J
jp9000 已提交
5211 5212 5213 5214
#define REPLAY_BUFFER_START \
	"==== Replay Buffer Start ==========================================="
#define REPLAY_BUFFER_STOP \
	"==== Replay Buffer Stop ============================================"
J
jp9000 已提交
5215 5216 5217 5218 5219
#define STREAMING_START \
	"==== Streaming Start ==============================================="
#define STREAMING_STOP \
	"==== Streaming Stop ================================================"

5220 5221
void OBSBasic::StartStreaming()
{
J
jp9000 已提交
5222 5223
	if (outputHandler->StreamingActive())
		return;
5224
	if (disableOutputsRef)
5225
		return;
J
jp9000 已提交
5226 5227 5228 5229

	if (api)
		api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);

5230 5231
	SaveProject();

J
jp9000 已提交
5232 5233
	ui->streamButton->setEnabled(false);
	ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
5234 5235 5236 5237 5238

	if (sysTrayStream) {
		sysTrayStream->setEnabled(false);
		sysTrayStream->setText(ui->streamButton->text());
	}
5239

J
jp9000 已提交
5240
	if (!outputHandler->StartStreaming(service)) {
J
jp9000 已提交
5241 5242 5243 5244
		QString message =
			!outputHandler->lastError.empty()
				? QTStr(outputHandler->lastError.c_str())
				: QTStr("Output.StartFailedGeneric");
J
jp9000 已提交
5245 5246
		ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
		ui->streamButton->setEnabled(true);
5247
		ui->streamButton->setChecked(false);
5248 5249 5250 5251 5252

		if (sysTrayStream) {
			sysTrayStream->setText(ui->streamButton->text());
			sysTrayStream->setEnabled(true);
		}
5253

5254
		QMessageBox::critical(this, QTStr("Output.StartStreamFailed"),
J
jp9000 已提交
5255
				      message);
5256
		return;
5257
	}
5258

J
jp9000 已提交
5259 5260
	bool recordWhenStreaming = config_get_bool(
		GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
5261 5262
	if (recordWhenStreaming)
		StartRecording();
5263

J
jp9000 已提交
5264 5265
	bool replayBufferWhileStreaming = config_get_bool(
		GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
5266 5267
	if (replayBufferWhileStreaming)
		StartReplayBuffer();
5268 5269
}

5270 5271 5272 5273
#ifdef _WIN32
static inline void UpdateProcessPriority()
{
	const char *priority = config_get_string(App()->GlobalConfig(),
J
jp9000 已提交
5274
						 "General", "ProcessPriority");
5275 5276 5277 5278 5279 5280 5281
	if (priority && strcmp(priority, "Normal") != 0)
		SetProcessPriority(priority);
}

static inline void ClearProcessPriority()
{
	const char *priority = config_get_string(App()->GlobalConfig(),
J
jp9000 已提交
5282
						 "General", "ProcessPriority");
5283 5284 5285 5286
	if (priority && strcmp(priority, "Normal") != 0)
		SetProcessPriority("Normal");
}
#else
J
jp9000 已提交
5287 5288 5289 5290 5291 5292
#define UpdateProcessPriority() \
	do {                    \
	} while (false)
#define ClearProcessPriority() \
	do {                   \
	} while (false)
5293 5294
#endif

5295
inline void OBSBasic::OnActivate()
5296
{
5297 5298
	if (ui->profileMenu->isEnabled()) {
		ui->profileMenu->setEnabled(false);
J
jp9000 已提交
5299
		ui->autoConfigure->setEnabled(false);
5300 5301
		App()->IncrementSleepInhibition();
		UpdateProcessPriority();
C
cg2121 已提交
5302

5303 5304 5305 5306 5307 5308 5309
#ifdef _WIN32
		taskProg->show();
		taskProg->resume();
		taskProg->setValue(1);
		taskBtn->setOverlayIcon(QIcon::fromTheme(
			"obs-active", QIcon(":/res/images/active.png")));
#endif
5310
		if (trayIcon)
J
jp9000 已提交
5311 5312 5313
			trayIcon->setIcon(QIcon::fromTheme(
				"obs-tray-active",
				QIcon(":/res/images/tray_active.png")));
5314 5315
	}
}
J
jp9000 已提交
5316

5317 5318 5319
extern volatile bool recording_paused;
extern volatile bool replaybuf_active;

5320 5321
inline void OBSBasic::OnDeactivate()
{
5322
	if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
J
jp9000 已提交
5323
		ui->profileMenu->setEnabled(true);
J
jp9000 已提交
5324
		ui->autoConfigure->setEnabled(true);
5325
		App()->DecrementSleepInhibition();
5326
		ClearProcessPriority();
C
cg2121 已提交
5327

5328
		if (trayIcon)
J
jp9000 已提交
5329 5330
			trayIcon->setIcon(QIcon::fromTheme(
				"obs-tray", QIcon(":/res/images/obs.png")));
5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358
#ifdef _WIN32
		taskProg->hide();
		taskBtn->clearOverlayIcon();
#endif
	} else {
		if (os_atomic_load_bool(&recording_paused)) {
#ifdef _WIN32
			taskProg->show();
			taskProg->pause();
			taskBtn->setOverlayIcon(QIcon::fromTheme(
				"obs-paused",
				QIcon(":/res/images/paused.png")));
#endif
			if (trayIcon)
				trayIcon->setIcon(
					QIcon(":/res/images/obs_paused.png"));
		} else {
#ifdef _WIN32
			taskProg->show();
			taskProg->resume();
			taskBtn->setOverlayIcon(QIcon::fromTheme(
				"obs-active",
				QIcon(":/res/images/active.png")));
#endif
			if (trayIcon)
				trayIcon->setIcon(
					QIcon(":/res/images/tray_active.png"));
		}
J
jp9000 已提交
5359
	}
5360 5361 5362 5363 5364 5365 5366
}

void OBSBasic::StopStreaming()
{
	SaveProject();

	if (outputHandler->StreamingActive())
5367
		outputHandler->StopStreaming(streamingStopping);
5368 5369

	OnDeactivate();
5370

J
jp9000 已提交
5371 5372 5373 5374 5375
	bool recordWhenStreaming = config_get_bool(
		GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
	bool keepRecordingWhenStreamStops =
		config_get_bool(GetGlobalConfig(), "BasicWindow",
				"KeepRecordingWhenStreamStops");
5376 5377
	if (recordWhenStreaming && !keepRecordingWhenStreamStops)
		StopRecording();
5378

J
jp9000 已提交
5379 5380 5381 5382 5383
	bool replayBufferWhileStreaming = config_get_bool(
		GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
	bool keepReplayBufferStreamStops =
		config_get_bool(GetGlobalConfig(), "BasicWindow",
				"KeepReplayBufferStreamStops");
5384 5385
	if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
		StopReplayBuffer();
5386 5387
}

J
jp9000 已提交
5388 5389 5390 5391 5392
void OBSBasic::ForceStopStreaming()
{
	SaveProject();

	if (outputHandler->StreamingActive())
5393
		outputHandler->StopStreaming(true);
J
jp9000 已提交
5394

5395
	OnDeactivate();
5396

J
jp9000 已提交
5397 5398 5399 5400 5401
	bool recordWhenStreaming = config_get_bool(
		GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
	bool keepRecordingWhenStreamStops =
		config_get_bool(GetGlobalConfig(), "BasicWindow",
				"KeepRecordingWhenStreamStops");
5402 5403
	if (recordWhenStreaming && !keepRecordingWhenStreamStops)
		StopRecording();
5404

J
jp9000 已提交
5405 5406 5407 5408 5409
	bool replayBufferWhileStreaming = config_get_bool(
		GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
	bool keepReplayBufferStreamStops =
		config_get_bool(GetGlobalConfig(), "BasicWindow",
				"KeepReplayBufferStreamStops");
5410 5411
	if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
		StopReplayBuffer();
J
jp9000 已提交
5412 5413 5414 5415 5416 5417
}

void OBSBasic::StreamDelayStarting(int sec)
{
	ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
	ui->streamButton->setEnabled(true);
5418
	ui->streamButton->setChecked(true);
5419 5420 5421 5422 5423

	if (sysTrayStream) {
		sysTrayStream->setText(ui->streamButton->text());
		sysTrayStream->setEnabled(true);
	}
J
jp9000 已提交
5424

5425 5426 5427 5428
	if (!startStreamMenu.isNull())
		startStreamMenu->deleteLater();

	startStreamMenu = new QMenu();
J
jp9000 已提交
5429 5430 5431 5432
	startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"), this,
				   SLOT(StopStreaming()));
	startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
				   SLOT(ForceStopStreaming()));
J
jp9000 已提交
5433 5434 5435
	ui->streamButton->setMenu(startStreamMenu);

	ui->statusbar->StreamDelayStarting(sec);
5436

5437
	OnActivate();
J
jp9000 已提交
5438 5439 5440 5441 5442 5443
}

void OBSBasic::StreamDelayStopping(int sec)
{
	ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
	ui->streamButton->setEnabled(true);
5444
	ui->streamButton->setChecked(false);
5445 5446 5447 5448 5449

	if (sysTrayStream) {
		sysTrayStream->setText(ui->streamButton->text());
		sysTrayStream->setEnabled(true);
	}
J
jp9000 已提交
5450

5451 5452 5453 5454
	if (!startStreamMenu.isNull())
		startStreamMenu->deleteLater();

	startStreamMenu = new QMenu();
J
jp9000 已提交
5455 5456 5457 5458
	startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"), this,
				   SLOT(StartStreaming()));
	startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
				   SLOT(ForceStopStreaming()));
J
jp9000 已提交
5459 5460 5461
	ui->streamButton->setMenu(startStreamMenu);

	ui->statusbar->StreamDelayStopping(sec);
5462 5463 5464

	if (api)
		api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
J
jp9000 已提交
5465 5466
}

5467
void OBSBasic::StreamingStart()
5468
{
5469
	ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
J
jp9000 已提交
5470
	ui->streamButton->setEnabled(true);
5471
	ui->streamButton->setChecked(true);
J
jp9000 已提交
5472
	ui->statusbar->StreamStarted(outputHandler->streamOutput);
5473 5474 5475 5476 5477

	if (sysTrayStream) {
		sysTrayStream->setText(ui->streamButton->text());
		sysTrayStream->setEnabled(true);
	}
5478

J
jp9000 已提交
5479 5480 5481
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);

5482
	OnActivate();
5483

5484
	blog(LOG_INFO, STREAMING_START);
5485 5486
}

5487 5488 5489
void OBSBasic::StreamStopping()
{
	ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
5490 5491 5492

	if (sysTrayStream)
		sysTrayStream->setText(ui->streamButton->text());
J
jp9000 已提交
5493

5494
	streamingStopping = true;
J
jp9000 已提交
5495 5496
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
5497 5498
}

5499
void OBSBasic::StreamingStop(int code, QString last_error)
5500
{
5501
	const char *errorDescription = "";
5502 5503
	DStr errorMessage;
	bool use_last_error = false;
5504
	bool encode_error = false;
5505 5506 5507

	switch (code) {
	case OBS_OUTPUT_BAD_PATH:
5508
		errorDescription = Str("Output.ConnectFail.BadPath");
5509 5510 5511
		break;

	case OBS_OUTPUT_CONNECT_FAILED:
5512 5513
		use_last_error = true;
		errorDescription = Str("Output.ConnectFail.ConnectFailed");
5514 5515 5516
		break;

	case OBS_OUTPUT_INVALID_STREAM:
5517
		errorDescription = Str("Output.ConnectFail.InvalidStream");
5518 5519
		break;

5520 5521 5522 5523
	case OBS_OUTPUT_ENCODE_ERROR:
		encode_error = true;
		break;

5524
	default:
5525
	case OBS_OUTPUT_ERROR:
5526 5527
		use_last_error = true;
		errorDescription = Str("Output.ConnectFail.Error");
5528 5529 5530 5531 5532
		break;

	case OBS_OUTPUT_DISCONNECTED:
		/* doesn't happen if output is set to reconnect.  note that
		 * reconnects are handled in the output, not in the UI */
5533 5534
		use_last_error = true;
		errorDescription = Str("Output.ConnectFail.Disconnected");
5535 5536
	}

5537 5538
	if (use_last_error && !last_error.isEmpty())
		dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
J
jp9000 已提交
5539
			    QT_TO_UTF8(last_error));
5540 5541 5542
	else
		dstr_copy(errorMessage, errorDescription);

J
jp9000 已提交
5543
	ui->statusbar->StreamStopped();
5544

5545
	ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
J
jp9000 已提交
5546
	ui->streamButton->setEnabled(true);
5547
	ui->streamButton->setChecked(false);
5548 5549 5550 5551 5552

	if (sysTrayStream) {
		sysTrayStream->setText(ui->streamButton->text());
		sysTrayStream->setEnabled(true);
	}
5553

5554
	streamingStopping = false;
J
jp9000 已提交
5555 5556 5557
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);

5558
	OnDeactivate();
5559 5560

	blog(LOG_INFO, STREAMING_STOP);
J
jp9000 已提交
5561

5562
	if (encode_error) {
J
jp9000 已提交
5563 5564 5565
		OBSMessageBox::information(
			this, QTStr("Output.StreamEncodeError.Title"),
			QTStr("Output.StreamEncodeError.Msg"));
5566 5567

	} else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
5568
		OBSMessageBox::information(this,
J
jp9000 已提交
5569 5570
					   QTStr("Output.ConnectFail.Title"),
					   QT_UTF8(errorMessage));
5571

C
cg2121 已提交
5572
	} else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
J
jp9000 已提交
5573 5574
		SysTrayNotify(QT_UTF8(errorDescription),
			      QSystemTrayIcon::Warning);
C
cg2121 已提交
5575
	}
J
jp9000 已提交
5576

5577 5578 5579 5580 5581
	if (!startStreamMenu.isNull()) {
		ui->streamButton->setMenu(nullptr);
		startStreamMenu->deleteLater();
		startStreamMenu = nullptr;
	}
J
jp9000 已提交
5582 5583
}

C
cg2121 已提交
5584 5585 5586
void OBSBasic::AutoRemux()
{
	const char *mode = config_get_string(basicConfig, "Output", "Mode");
5587 5588
	bool advanced = astrcmpi(mode, "Advanced") == 0;

J
jp9000 已提交
5589 5590 5591 5592 5593
	const char *path = !advanced ? config_get_string(basicConfig,
							 "SimpleOutput",
							 "FilePath")
				     : config_get_string(basicConfig, "AdvOut",
							 "RecFilePath");
5594

5595 5596
	/* do not save if using FFmpeg output in advanced output mode */
	if (advanced) {
J
jp9000 已提交
5597 5598
		const char *type =
			config_get_string(basicConfig, "AdvOut", "RecType");
5599 5600 5601 5602 5603
		if (astrcmpi(type, "FFmpeg") == 0) {
			return;
		}
	}

J
jp9000 已提交
5604 5605 5606 5607 5608 5609 5610
	QString input;
	input += path;
	input += "/";
	input += remuxFilename.c_str();

	QFileInfo fi(remuxFilename.c_str());

5611 5612 5613 5614 5615
	/* do not remux if lossless */
	if (fi.suffix().compare("avi", Qt::CaseInsensitive) == 0) {
		return;
	}

J
jp9000 已提交
5616 5617 5618 5619 5620
	QString output;
	output += path;
	output += "/";
	output += fi.completeBaseName();
	output += ".mp4";
C
cg2121 已提交
5621 5622 5623

	OBSRemux *remux = new OBSRemux(path, this, true);
	remux->show();
J
jp9000 已提交
5624
	remux->AutoRemux(input, output);
C
cg2121 已提交
5625 5626
}

5627 5628
void OBSBasic::StartRecording()
{
5629 5630
	if (outputHandler->RecordingActive())
		return;
5631
	if (disableOutputsRef)
5632
		return;
5633

5634 5635 5636 5637 5638 5639
	if (!OutputPathValid()) {
		OutputPathInvalidMessage();
		ui->recordButton->setChecked(false);
		return;
	}

5640 5641 5642 5643 5644 5645
	if (LowDiskSpace()) {
		DiskSpaceMessage();
		ui->recordButton->setChecked(false);
		return;
	}

J
jp9000 已提交
5646 5647 5648
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);

5649
	SaveProject();
5650 5651 5652

	if (!outputHandler->StartRecording())
		ui->recordButton->setChecked(false);
5653 5654
}

5655 5656
void OBSBasic::RecordStopping()
{
J
jp9000 已提交
5657
	ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
5658 5659 5660

	if (sysTrayRecord)
		sysTrayRecord->setText(ui->recordButton->text());
J
jp9000 已提交
5661

5662
	recordingStopping = true;
J
jp9000 已提交
5663 5664
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
5665 5666
}

5667 5668 5669 5670 5671
void OBSBasic::StopRecording()
{
	SaveProject();

	if (outputHandler->RecordingActive())
5672
		outputHandler->StopRecording(recordingStopping);
J
jp9000 已提交
5673

5674
	OnDeactivate();
5675 5676
}

P
Palana 已提交
5677 5678
void OBSBasic::RecordingStart()
{
J
jp9000 已提交
5679
	ui->statusbar->RecordingStarted(outputHandler->fileOutput);
J
jp9000 已提交
5680
	ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
5681
	ui->recordButton->setChecked(true);
5682 5683 5684

	if (sysTrayRecord)
		sysTrayRecord->setText(ui->recordButton->text());
5685

5686
	recordingStopping = false;
J
jp9000 已提交
5687 5688 5689
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);

5690 5691 5692
	if (!diskFullTimer->isActive())
		diskFullTimer->start(1000);

5693
	OnActivate();
J
jp9000 已提交
5694
	UpdatePause();
5695

5696
	blog(LOG_INFO, RECORDING_START);
P
Palana 已提交
5697 5698
}

5699
void OBSBasic::RecordingStop(int code, QString last_error)
5700
{
P
Palana 已提交
5701
	ui->statusbar->RecordingStopped();
J
jp9000 已提交
5702
	ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
5703
	ui->recordButton->setChecked(false);
5704 5705 5706

	if (sysTrayRecord)
		sysTrayRecord->setText(ui->recordButton->text());
J
jp9000 已提交
5707

5708
	blog(LOG_INFO, RECORDING_STOP);
5709

C
cg2121 已提交
5710
	if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
J
jp9000 已提交
5711 5712
		OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
					QTStr("Output.RecordFail.Unsupported"));
J
jp9000 已提交
5713

5714
	} else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
J
jp9000 已提交
5715 5716 5717
		OBSMessageBox::warning(
			this, QTStr("Output.RecordError.Title"),
			QTStr("Output.RecordError.EncodeErrorMsg"));
5718

C
cg2121 已提交
5719
	} else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
5720
		OBSMessageBox::warning(this,
J
jp9000 已提交
5721 5722
				       QTStr("Output.RecordNoSpace.Title"),
				       QTStr("Output.RecordNoSpace.Msg"));
J
jp9000 已提交
5723

C
cg2121 已提交
5724
	} else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
5725 5726 5727 5728 5729 5730 5731 5732 5733

		const char *errorDescription;
		DStr errorMessage;
		bool use_last_error = true;

		errorDescription = Str("Output.RecordError.Msg");

		if (use_last_error && !last_error.isEmpty())
			dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
J
jp9000 已提交
5734
				    QT_TO_UTF8(last_error));
5735 5736 5737
		else
			dstr_copy(errorMessage, errorDescription);

J
jp9000 已提交
5738 5739
		OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
					QT_UTF8(errorMessage));
C
cg2121 已提交
5740 5741 5742

	} else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
		SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
J
jp9000 已提交
5743
			      QSystemTrayIcon::Warning);
C
cg2121 已提交
5744 5745 5746

	} else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
		SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
J
jp9000 已提交
5747
			      QSystemTrayIcon::Warning);
C
cg2121 已提交
5748 5749 5750

	} else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
		SysTrayNotify(QTStr("Output.RecordError.Msg"),
J
jp9000 已提交
5751
			      QSystemTrayIcon::Warning);
J
jp9000 已提交
5752 5753
	}

J
jp9000 已提交
5754 5755 5756
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);

5757 5758 5759
	if (diskFullTimer->isActive())
		diskFullTimer->stop();

C
cg2121 已提交
5760 5761 5762
	if (remuxAfterRecord)
		AutoRemux();

5763
	OnDeactivate();
J
jp9000 已提交
5764
	UpdatePause(false);
5765
}
5766

J
jp9000 已提交
5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797
void OBSBasic::ShowReplayBufferPauseWarning()
{
	auto msgBox = []() {
		QMessageBox msgbox(App()->GetMainWindow());
		msgbox.setWindowTitle(QTStr("Output.ReplayBuffer."
					    "PauseWarning.Title"));
		msgbox.setText(QTStr("Output.ReplayBuffer."
				     "PauseWarning.Text"));
		msgbox.setIcon(QMessageBox::Icon::Information);
		msgbox.addButton(QMessageBox::Ok);

		QCheckBox *cb = new QCheckBox(QTStr("DoNotShowAgain"));
		msgbox.setCheckBox(cb);

		msgbox.exec();

		if (cb->isChecked()) {
			config_set_bool(App()->GlobalConfig(), "General",
					"WarnedAboutReplayBufferPausing", true);
			config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
		}
	};

	bool warned = config_get_bool(App()->GlobalConfig(), "General",
				      "WarnedAboutReplayBufferPausing");
	if (!warned) {
		QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection,
					  Q_ARG(VoidFunc, msgBox));
	}
}

J
jp9000 已提交
5798 5799 5800 5801 5802 5803
void OBSBasic::StartReplayBuffer()
{
	if (!outputHandler || !outputHandler->replayBuffer)
		return;
	if (outputHandler->ReplayBufferActive())
		return;
5804
	if (disableOutputsRef)
5805
		return;
J
jp9000 已提交
5806

J
JohannMG 已提交
5807
	if (!UIValidation::NoSourcesConfirmation(this)) {
5808 5809 5810 5811
		replayBufferButton->setChecked(false);
		return;
	}

5812 5813 5814 5815 5816 5817
	if (LowDiskSpace()) {
		DiskSpaceMessage();
		replayBufferButton->setChecked(false);
		return;
	}

J
jp9000 已提交
5818 5819 5820 5821
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);

	SaveProject();
J
jp9000 已提交
5822 5823

	if (!outputHandler->StartReplayBuffer()) {
5824
		replayBufferButton->setChecked(false);
J
jp9000 已提交
5825 5826 5827
	} else if (os_atomic_load_bool(&recording_paused)) {
		ShowReplayBufferPauseWarning();
	}
J
jp9000 已提交
5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863
}

void OBSBasic::ReplayBufferStopping()
{
	if (!outputHandler || !outputHandler->replayBuffer)
		return;

	replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer"));

	if (sysTrayReplayBuffer)
		sysTrayReplayBuffer->setText(replayBufferButton->text());

	replayBufferStopping = true;
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING);
}

void OBSBasic::StopReplayBuffer()
{
	if (!outputHandler || !outputHandler->replayBuffer)
		return;

	SaveProject();

	if (outputHandler->ReplayBufferActive())
		outputHandler->StopReplayBuffer(replayBufferStopping);

	OnDeactivate();
}

void OBSBasic::ReplayBufferStart()
{
	if (!outputHandler || !outputHandler->replayBuffer)
		return;

	replayBufferButton->setText(QTStr("Basic.Main.StopReplayBuffer"));
5864
	replayBufferButton->setChecked(true);
J
jp9000 已提交
5865 5866 5867 5868 5869 5870 5871 5872 5873

	if (sysTrayReplayBuffer)
		sysTrayReplayBuffer->setText(replayBufferButton->text());

	replayBufferStopping = false;
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);

	OnActivate();
5874
	UpdateReplayBuffer();
J
jp9000 已提交
5875 5876 5877 5878

	blog(LOG_INFO, REPLAY_BUFFER_START);
}

5879 5880 5881 5882 5883 5884 5885 5886
void OBSBasic::ReplayBufferSave()
{
	if (!outputHandler || !outputHandler->replayBuffer)
		return;
	if (!outputHandler->ReplayBufferActive())
		return;

	calldata_t cd = {0};
J
jp9000 已提交
5887 5888
	proc_handler_t *ph =
		obs_output_get_proc_handler(outputHandler->replayBuffer);
5889 5890 5891 5892
	proc_handler_call(ph, "save", &cd);
	calldata_free(&cd);
}

J
jp9000 已提交
5893 5894 5895 5896 5897 5898
void OBSBasic::ReplayBufferStop(int code)
{
	if (!outputHandler || !outputHandler->replayBuffer)
		return;

	replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
5899
	replayBufferButton->setChecked(false);
J
jp9000 已提交
5900 5901 5902 5903 5904 5905 5906

	if (sysTrayReplayBuffer)
		sysTrayReplayBuffer->setText(replayBufferButton->text());

	blog(LOG_INFO, REPLAY_BUFFER_STOP);

	if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
J
jp9000 已提交
5907 5908
		OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
					QTStr("Output.RecordFail.Unsupported"));
J
jp9000 已提交
5909 5910

	} else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
5911
		OBSMessageBox::warning(this,
J
jp9000 已提交
5912 5913
				       QTStr("Output.RecordNoSpace.Title"),
				       QTStr("Output.RecordNoSpace.Msg"));
J
jp9000 已提交
5914 5915

	} else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
J
jp9000 已提交
5916 5917
		OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
					QTStr("Output.RecordError.Msg"));
J
jp9000 已提交
5918 5919 5920

	} else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
		SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
J
jp9000 已提交
5921
			      QSystemTrayIcon::Warning);
J
jp9000 已提交
5922 5923 5924

	} else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
		SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
J
jp9000 已提交
5925
			      QSystemTrayIcon::Warning);
J
jp9000 已提交
5926 5927 5928

	} else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
		SysTrayNotify(QTStr("Output.RecordError.Msg"),
J
jp9000 已提交
5929
			      QSystemTrayIcon::Warning);
J
jp9000 已提交
5930 5931 5932 5933 5934 5935
	}

	if (api)
		api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);

	OnDeactivate();
5936
	UpdateReplayBuffer(false);
J
jp9000 已提交
5937 5938
}

5939 5940
void OBSBasic::on_streamButton_clicked()
{
J
jp9000 已提交
5941
	if (outputHandler->StreamingActive()) {
5942
		bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
J
jp9000 已提交
5943
					       "WarnBeforeStoppingStream");
5944

C
cg2121 已提交
5945
		if (confirm && isVisible()) {
5946
			QMessageBox::StandardButton button =
J
jp9000 已提交
5947 5948
				OBSMessageBox::question(
					this, QTStr("ConfirmStop.Title"),
5949 5950 5951
					QTStr("ConfirmStop.Text"),
					QMessageBox::Yes | QMessageBox::No,
					QMessageBox::No);
5952

C
cg2121 已提交
5953 5954
			if (button == QMessageBox::No) {
				ui->streamButton->setChecked(true);
5955
				return;
C
cg2121 已提交
5956
			}
5957 5958
		}

5959
		StopStreaming();
5960
	} else {
J
JohannMG 已提交
5961
		if (!UIValidation::NoSourcesConfirmation(this)) {
5962 5963 5964 5965
			ui->streamButton->setChecked(false);
			return;
		}

5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979
		auto action =
			UIValidation::StreamSettingsConfirmation(this, service);
		switch (action) {
		case StreamSettingsAction::ContinueStream:
			break;
		case StreamSettingsAction::OpenSettings:
			on_action_Settings_triggered();
			ui->streamButton->setChecked(false);
			return;
		case StreamSettingsAction::Cancel:
			ui->streamButton->setChecked(false);
			return;
		}

5980
		bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
J
jp9000 已提交
5981
					       "WarnBeforeStartingStream");
5982

5983 5984 5985 5986 5987 5988
		obs_data_t *settings = obs_service_get_settings(service);
		bool bwtest = obs_data_get_bool(settings, "bwtest");
		obs_data_release(settings);

		if (bwtest && isVisible()) {
			QMessageBox::StandardButton button =
J
jp9000 已提交
5989 5990 5991
				OBSMessageBox::question(
					this, QTStr("ConfirmBWTest.Title"),
					QTStr("ConfirmBWTest.Text"));
5992 5993 5994 5995 5996 5997

			if (button == QMessageBox::No) {
				ui->streamButton->setChecked(false);
				return;
			}
		} else if (confirm && isVisible()) {
5998
			QMessageBox::StandardButton button =
J
jp9000 已提交
5999 6000
				OBSMessageBox::question(
					this, QTStr("ConfirmStart.Title"),
6001 6002 6003
					QTStr("ConfirmStart.Text"),
					QMessageBox::Yes | QMessageBox::No,
					QMessageBox::No);
6004

C
cg2121 已提交
6005 6006
			if (button == QMessageBox::No) {
				ui->streamButton->setChecked(false);
6007
				return;
C
cg2121 已提交
6008
			}
6009 6010
		}

6011
		StartStreaming();
6012 6013 6014 6015 6016
	}
}

void OBSBasic::on_recordButton_clicked()
{
6017
	if (outputHandler->RecordingActive()) {
6018 6019 6020 6021 6022 6023 6024
		bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
					       "WarnBeforeStoppingRecord");

		if (confirm && isVisible()) {
			QMessageBox::StandardButton button =
				OBSMessageBox::question(
					this, QTStr("ConfirmStopRecord.Title"),
6025 6026 6027
					QTStr("ConfirmStopRecord.Text"),
					QMessageBox::Yes | QMessageBox::No,
					QMessageBox::No);
6028 6029 6030 6031 6032 6033

			if (button == QMessageBox::No) {
				ui->recordButton->setChecked(true);
				return;
			}
		}
6034
		StopRecording();
6035
	} else {
J
JohannMG 已提交
6036
		if (!UIValidation::NoSourcesConfirmation(this)) {
6037 6038 6039 6040
			ui->recordButton->setChecked(false);
			return;
		}

6041
		StartRecording();
6042
	}
J
jp9000 已提交
6043 6044
}

J
jp9000 已提交
6045
void OBSBasic::on_settingsButton_clicked()
J
jp9000 已提交
6046
{
J
jp9000 已提交
6047
	on_action_Settings_triggered();
J
jp9000 已提交
6048
}
6049

6050 6051 6052 6053 6054 6055
void OBSBasic::on_actionHelpPortal_triggered()
{
	QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
	QDesktopServices::openUrl(url);
}

6056 6057 6058 6059 6060 6061
void OBSBasic::on_actionWebsite_triggered()
{
	QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
	QDesktopServices::openUrl(url);
}

6062 6063
void OBSBasic::on_actionDiscord_triggered()
{
6064
	QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
6065 6066 6067
	QDesktopServices::openUrl(url);
}

6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087
void OBSBasic::on_actionShowSettingsFolder_triggered()
{
	char path[512];
	int ret = GetConfigPath(path, 512, "obs-studio");
	if (ret <= 0)
		return;

	QDesktopServices::openUrl(QUrl::fromLocalFile(path));
}

void OBSBasic::on_actionShowProfileFolder_triggered()
{
	char path[512];
	int ret = GetProfilePath(path, 512, "");
	if (ret <= 0)
		return;

	QDesktopServices::openUrl(QUrl::fromLocalFile(path));
}

J
jp9000 已提交
6088
int OBSBasic::GetTopSelectedSourceItem()
6089
{
J
jp9000 已提交
6090 6091 6092
	QModelIndexList selectedItems =
		ui->sources->selectionModel()->selectedIndexes();
	return selectedItems.count() ? selectedItems[0].row() : -1;
6093 6094
}

6095 6096 6097 6098 6099
QModelIndexList OBSBasic::GetAllSelectedSourceItems()
{
	return ui->sources->selectionModel()->selectedIndexes();
}

J
jp9000 已提交
6100 6101
void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
{
6102
	CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
J
jp9000 已提交
6103 6104 6105 6106

	UNUSED_PARAMETER(pos);
}

J
jp9000 已提交
6107
void OBSBasic::on_program_customContextMenuRequested(const QPoint &)
R
Ryan Foster 已提交
6108 6109 6110 6111
{
	QMenu popup(this);
	QPointer<QMenu> studioProgramProjector;

J
jp9000 已提交
6112
	studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
R
Ryan Foster 已提交
6113
	AddProjectorMenuMonitors(studioProgramProjector, this,
J
jp9000 已提交
6114
				 SLOT(OpenStudioProgramProjector()));
R
Ryan Foster 已提交
6115 6116 6117

	popup.addMenu(studioProgramProjector);

J
jp9000 已提交
6118 6119 6120
	QAction *studioProgramWindow =
		popup.addAction(QTStr("StudioProgramWindow"), this,
				SLOT(OpenStudioProgramWindow()));
R
Ryan Foster 已提交
6121 6122 6123 6124 6125 6126

	popup.addAction(studioProgramWindow);

	popup.exec(QCursor::pos());
}

6127
void OBSBasic::PreviewDisabledMenu(const QPoint &pos)
J
jp9000 已提交
6128 6129
{
	QMenu popup(this);
6130
	delete previewProjectorMain;
J
jp9000 已提交
6131

J
jp9000 已提交
6132 6133 6134
	QAction *action =
		popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
				this, SLOT(TogglePreview()));
J
jp9000 已提交
6135
	action->setCheckable(true);
6136
	action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
J
jp9000 已提交
6137

6138
	previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
P
pkv 已提交
6139
	AddProjectorMenuMonitors(previewProjectorMain, this,
J
jp9000 已提交
6140
				 SLOT(OpenPreviewProjector()));
J
jp9000 已提交
6141

J
jp9000 已提交
6142 6143
	QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
						 SLOT(OpenPreviewWindow()));
C
cg2121 已提交
6144

P
pkv 已提交
6145
	popup.addMenu(previewProjectorMain);
C
cg2121 已提交
6146
	popup.addAction(previewWindow);
J
jp9000 已提交
6147 6148 6149 6150 6151
	popup.exec(QCursor::pos());

	UNUSED_PARAMETER(pos);
}

6152 6153
void OBSBasic::on_actionAlwaysOnTop_triggered()
{
6154
#ifndef _WIN32
6155 6156 6157 6158
	/* Make sure all dialogs are safely and successfully closed before
	 * switching the always on top mode due to the fact that windows all
	 * have to be recreated, so queue the actual toggle to happen after
	 * all events related to closing the dialogs have finished */
6159 6160 6161
	CloseDialogs();
#endif

6162
	QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
J
jp9000 已提交
6163
				  Qt::QueuedConnection);
6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175
}

void OBSBasic::ToggleAlwaysOnTop()
{
	bool isAlwaysOnTop = IsAlwaysOnTop(this);

	ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
	SetAlwaysOnTop(this, !isAlwaysOnTop);

	show();
}

6176 6177 6178 6179 6180 6181 6182 6183 6184 6185
void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const
{
	const char *val = config_get_string(basicConfig, "Video", "FPSCommon");

	if (strcmp(val, "10") == 0) {
		num = 10;
		den = 1;
	} else if (strcmp(val, "20") == 0) {
		num = 20;
		den = 1;
J
jp9000 已提交
6186 6187 6188
	} else if (strcmp(val, "24 NTSC") == 0) {
		num = 24000;
		den = 1001;
6189
	} else if (strcmp(val, "25 PAL") == 0) {
6190 6191 6192 6193 6194 6195 6196 6197
		num = 25;
		den = 1;
	} else if (strcmp(val, "29.97") == 0) {
		num = 30000;
		den = 1001;
	} else if (strcmp(val, "48") == 0) {
		num = 48;
		den = 1;
6198 6199 6200
	} else if (strcmp(val, "50 PAL") == 0) {
		num = 50;
		den = 1;
6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244
	} else if (strcmp(val, "59.94") == 0) {
		num = 60000;
		den = 1001;
	} else if (strcmp(val, "60") == 0) {
		num = 60;
		den = 1;
	} else {
		num = 30;
		den = 1;
	}
}

void OBSBasic::GetFPSInteger(uint32_t &num, uint32_t &den) const
{
	num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSInt");
	den = 1;
}

void OBSBasic::GetFPSFraction(uint32_t &num, uint32_t &den) const
{
	num = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNum");
	den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSDen");
}

void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const
{
	num = 1000000000;
	den = (uint32_t)config_get_uint(basicConfig, "Video", "FPSNS");
}

void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const
{
	uint32_t type = config_get_uint(basicConfig, "Video", "FPSType");

	if (type == 1) //"Integer"
		GetFPSInteger(num, den);
	else if (type == 2) //"Fraction"
		GetFPSFraction(num, den);
	else if (false) //"Nanoseconds", currently not implemented
		GetFPSNanoseconds(num, den);
	else
		GetFPSCommon(num, den);
}

6245
config_t *OBSBasic::Config() const
6246 6247 6248
{
	return basicConfig;
}
J
jp9000 已提交
6249 6250 6251

void OBSBasic::on_actionEditTransform_triggered()
{
6252 6253 6254
	if (transformWindow)
		transformWindow->close();

6255 6256 6257
	if (!GetCurrentSceneItem())
		return;

J
jp9000 已提交
6258 6259
	transformWindow = new OBSBasicTransform(this);
	transformWindow->show();
6260
	transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
J
jp9000 已提交
6261 6262
}

6263 6264 6265 6266 6267
static obs_transform_info copiedTransformInfo;
static obs_sceneitem_crop copiedCropInfo;

void OBSBasic::on_actionCopyTransform_triggered()
{
J
jp9000 已提交
6268
	auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287
		if (!obs_sceneitem_selected(item))
			return true;

		obs_sceneitem_defer_update_begin(item);
		obs_sceneitem_get_info(item, &copiedTransformInfo);
		obs_sceneitem_get_crop(item, &copiedCropInfo);
		obs_sceneitem_defer_update_end(item);

		UNUSED_PARAMETER(scene);
		UNUSED_PARAMETER(param);
		return true;
	};

	obs_scene_enum_items(GetCurrentScene(), func, nullptr);
	ui->actionPasteTransform->setEnabled(true);
}

void OBSBasic::on_actionPasteTransform_triggered()
{
J
jp9000 已提交
6288
	auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304
		if (!obs_sceneitem_selected(item))
			return true;

		obs_sceneitem_defer_update_begin(item);
		obs_sceneitem_set_info(item, &copiedTransformInfo);
		obs_sceneitem_set_crop(item, &copiedCropInfo);
		obs_sceneitem_defer_update_end(item);

		UNUSED_PARAMETER(scene);
		UNUSED_PARAMETER(param);
		return true;
	};

	obs_scene_enum_items(GetCurrentScene(), func, nullptr);
}

6305
static bool reset_tr(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
J
jp9000 已提交
6306
{
6307 6308 6309 6310
	if (obs_sceneitem_is_group(item))
		obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
	if (!obs_sceneitem_selected(item))
		return true;
6311 6312
	if (obs_sceneitem_locked(item))
		return true;
J
jp9000 已提交
6313

6314
	obs_sceneitem_defer_update_begin(item);
J
jp9000 已提交
6315

6316 6317 6318 6319 6320 6321 6322 6323 6324
	obs_transform_info info;
	vec2_set(&info.pos, 0.0f, 0.0f);
	vec2_set(&info.scale, 1.0f, 1.0f);
	info.rot = 0.0f;
	info.alignment = OBS_ALIGN_TOP | OBS_ALIGN_LEFT;
	info.bounds_type = OBS_BOUNDS_NONE;
	info.bounds_alignment = OBS_ALIGN_CENTER;
	vec2_set(&info.bounds, 0.0f, 0.0f);
	obs_sceneitem_set_info(item, &info);
J
jp9000 已提交
6325

6326 6327
	obs_sceneitem_crop crop = {};
	obs_sceneitem_set_crop(item, &crop);
J
jp9000 已提交
6328

6329
	obs_sceneitem_defer_update_end(item);
J
jp9000 已提交
6330

6331 6332 6333 6334
	UNUSED_PARAMETER(scene);
	UNUSED_PARAMETER(param);
	return true;
}
J
jp9000 已提交
6335

6336 6337 6338
void OBSBasic::on_actionResetTransform_triggered()
{
	obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
J
jp9000 已提交
6339 6340
}

6341
static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
J
jp9000 已提交
6342 6343 6344 6345 6346
{
	matrix4 boxTransform;
	obs_sceneitem_get_box_transform(item, &boxTransform);

	vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
6347
	vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
J
jp9000 已提交
6348

J
jp9000 已提交
6349
	auto GetMinPos = [&](float x, float y) {
J
jp9000 已提交
6350 6351 6352
		vec3 pos;
		vec3_set(&pos, x, y, 0.0f);
		vec3_transform(&pos, &pos, &boxTransform);
6353 6354
		vec3_min(&tl, &tl, &pos);
		vec3_max(&br, &br, &pos);
J
jp9000 已提交
6355 6356
	};

6357 6358 6359 6360 6361 6362
	GetMinPos(0.0f, 0.0f);
	GetMinPos(1.0f, 0.0f);
	GetMinPos(0.0f, 1.0f);
	GetMinPos(1.0f, 1.0f);
}

6363
static vec3 GetItemTL(obs_sceneitem_t *item)
6364 6365 6366
{
	vec3 tl, br;
	GetItemBox(item, tl, br);
J
jp9000 已提交
6367 6368 6369
	return tl;
}

6370
static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
J
jp9000 已提交
6371 6372 6373 6374
{
	vec3 newTL;
	vec2 pos;

J
jp9000 已提交
6375
	obs_sceneitem_get_pos(item, &pos);
J
jp9000 已提交
6376 6377 6378
	newTL = GetItemTL(item);
	pos.x += tl.x - newTL.x;
	pos.y += tl.y - newTL.y;
J
jp9000 已提交
6379
	obs_sceneitem_set_pos(item, &pos);
J
jp9000 已提交
6380 6381
}

6382
static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
J
jp9000 已提交
6383
				  void *param)
J
jp9000 已提交
6384
{
6385 6386
	if (obs_sceneitem_is_group(item))
		obs_sceneitem_group_enum_items(item, RotateSelectedSources,
J
jp9000 已提交
6387
					       param);
J
jp9000 已提交
6388 6389
	if (!obs_sceneitem_selected(item))
		return true;
6390 6391
	if (obs_sceneitem_locked(item))
		return true;
J
jp9000 已提交
6392

J
jp9000 已提交
6393
	float rot = *reinterpret_cast<float *>(param);
J
jp9000 已提交
6394 6395 6396

	vec3 tl = GetItemTL(item);

J
jp9000 已提交
6397
	rot += obs_sceneitem_get_rot(item);
J
jp9000 已提交
6398 6399 6400 6401
	if (rot >= 360.0f)
		rot -= 360.0f;
	else if (rot <= -360.0f)
		rot += 360.0f;
J
jp9000 已提交
6402
	obs_sceneitem_set_rot(item, rot);
J
jp9000 已提交
6403

6404 6405
	obs_sceneitem_force_update_transform(item);

J
jp9000 已提交
6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429
	SetItemTL(item, tl);

	UNUSED_PARAMETER(scene);
	return true;
};

void OBSBasic::on_actionRotate90CW_triggered()
{
	float f90CW = 90.0f;
	obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW);
}

void OBSBasic::on_actionRotate90CCW_triggered()
{
	float f90CCW = -90.0f;
	obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW);
}

void OBSBasic::on_actionRotate180_triggered()
{
	float f180 = 180.0f;
	obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180);
}

6430
static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
J
jp9000 已提交
6431
				      void *param)
J
jp9000 已提交
6432
{
J
jp9000 已提交
6433
	vec2 &mul = *reinterpret_cast<vec2 *>(param);
J
jp9000 已提交
6434

6435 6436
	if (obs_sceneitem_is_group(item))
		obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
J
jp9000 已提交
6437
					       param);
J
jp9000 已提交
6438 6439
	if (!obs_sceneitem_selected(item))
		return true;
6440 6441
	if (obs_sceneitem_locked(item))
		return true;
J
jp9000 已提交
6442 6443 6444 6445

	vec3 tl = GetItemTL(item);

	vec2 scale;
J
jp9000 已提交
6446
	obs_sceneitem_get_scale(item, &scale);
J
jp9000 已提交
6447
	vec2_mul(&scale, &scale, &mul);
J
jp9000 已提交
6448
	obs_sceneitem_set_scale(item, &scale);
J
jp9000 已提交
6449

6450 6451
	obs_sceneitem_force_update_transform(item);

J
jp9000 已提交
6452
	SetItemTL(item, tl);
J
jp9000 已提交
6453 6454

	UNUSED_PARAMETER(scene);
J
jp9000 已提交
6455 6456 6457 6458 6459
	return true;
}

void OBSBasic::on_actionFlipHorizontal_triggered()
{
J
jp9000 已提交
6460 6461
	vec2 scale;
	vec2_set(&scale, -1.0f, 1.0f);
J
jp9000 已提交
6462
	obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
J
jp9000 已提交
6463
			     &scale);
J
jp9000 已提交
6464 6465 6466 6467
}

void OBSBasic::on_actionFlipVertical_triggered()
{
J
jp9000 已提交
6468 6469
	vec2 scale;
	vec2_set(&scale, 1.0f, -1.0f);
J
jp9000 已提交
6470
	obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
J
jp9000 已提交
6471
			     &scale);
J
jp9000 已提交
6472 6473
}

6474
static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
J
jp9000 已提交
6475
				     void *param)
J
jp9000 已提交
6476
{
J
jp9000 已提交
6477 6478
	obs_bounds_type boundsType =
		*reinterpret_cast<obs_bounds_type *>(param);
J
jp9000 已提交
6479

6480 6481
	if (obs_sceneitem_is_group(item))
		obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
J
jp9000 已提交
6482
					       param);
J
jp9000 已提交
6483 6484
	if (!obs_sceneitem_selected(item))
		return true;
6485 6486
	if (obs_sceneitem_locked(item))
		return true;
J
jp9000 已提交
6487 6488 6489 6490

	obs_video_info ovi;
	obs_get_video_info(&ovi);

6491
	obs_transform_info itemInfo;
J
jp9000 已提交
6492 6493 6494 6495 6496
	vec2_set(&itemInfo.pos, 0.0f, 0.0f);
	vec2_set(&itemInfo.scale, 1.0f, 1.0f);
	itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP;
	itemInfo.rot = 0.0f;

J
jp9000 已提交
6497 6498
	vec2_set(&itemInfo.bounds, float(ovi.base_width),
		 float(ovi.base_height));
J
jp9000 已提交
6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511
	itemInfo.bounds_type = boundsType;
	itemInfo.bounds_alignment = OBS_ALIGN_CENTER;

	obs_sceneitem_set_info(item, &itemInfo);

	UNUSED_PARAMETER(scene);
	return true;
}

void OBSBasic::on_actionFitToScreen_triggered()
{
	obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER;
	obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
J
jp9000 已提交
6512
			     &boundsType);
J
jp9000 已提交
6513 6514 6515 6516 6517 6518
}

void OBSBasic::on_actionStretchToScreen_triggered()
{
	obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
	obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
J
jp9000 已提交
6519
			     &boundsType);
J
jp9000 已提交
6520 6521
}

6522 6523 6524
enum class CenterType {
	Scene,
	Vertical,
J
jp9000 已提交
6525
	Horizontal,
6526 6527 6528
};

static bool center_to_scene(obs_scene_t *, obs_sceneitem_t *item, void *param)
J
jp9000 已提交
6529
{
J
jp9000 已提交
6530
	CenterType centerType = *reinterpret_cast<CenterType *>(param);
6531

6532 6533
	vec3 tl, br, itemCenter, screenCenter, offset;
	obs_video_info ovi;
6534
	obs_transform_info oti;
6535

6536
	if (obs_sceneitem_is_group(item))
6537
		obs_sceneitem_group_enum_items(item, center_to_scene,
J
jp9000 已提交
6538
					       &centerType);
6539 6540
	if (!obs_sceneitem_selected(item))
		return true;
6541 6542
	if (obs_sceneitem_locked(item))
		return true;
6543

6544
	obs_get_video_info(&ovi);
6545 6546 6547 6548
	obs_sceneitem_get_info(item, &oti);

	if (centerType == CenterType::Scene)
		vec3_set(&screenCenter, float(ovi.base_width),
J
jp9000 已提交
6549
			 float(ovi.base_height), 0.0f);
6550 6551
	else if (centerType == CenterType::Vertical)
		vec3_set(&screenCenter, float(oti.bounds.x),
J
jp9000 已提交
6552
			 float(ovi.base_height), 0.0f);
6553 6554
	else if (centerType == CenterType::Horizontal)
		vec3_set(&screenCenter, float(ovi.base_width),
J
jp9000 已提交
6555
			 float(oti.bounds.y), 0.0f);
6556

6557
	vec3_mulf(&screenCenter, &screenCenter, 0.5f);
6558

6559
	GetItemBox(item, tl, br);
6560

6561 6562 6563
	vec3_sub(&itemCenter, &br, &tl);
	vec3_mulf(&itemCenter, &itemCenter, 0.5f);
	vec3_add(&itemCenter, &itemCenter, &tl);
6564

6565 6566
	vec3_sub(&offset, &screenCenter, &itemCenter);
	vec3_add(&tl, &tl, &offset);
6567

6568 6569 6570 6571 6572
	if (centerType == CenterType::Vertical)
		tl.x = oti.pos.x;
	else if (centerType == CenterType::Horizontal)
		tl.y = oti.pos.y;

6573 6574 6575
	SetItemTL(item, tl);
	return true;
};
6576

6577 6578
void OBSBasic::on_actionCenterToScreen_triggered()
{
6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592
	CenterType centerType = CenterType::Scene;
	obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
}

void OBSBasic::on_actionVerticalCenter_triggered()
{
	CenterType centerType = CenterType::Vertical;
	obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
}

void OBSBasic::on_actionHorizontalCenter_triggered()
{
	CenterType centerType = CenterType::Horizontal;
	obs_scene_enum_items(GetCurrentScene(), center_to_scene, &centerType);
J
jp9000 已提交
6593
}
J
jp9000 已提交
6594

6595 6596 6597 6598
void OBSBasic::EnablePreviewDisplay(bool enable)
{
	obs_display_set_enabled(ui->preview->GetDisplay(), enable);
	ui->preview->setVisible(enable);
6599
	ui->previewDisabledWidget->setVisible(!enable);
6600 6601
}

J
jp9000 已提交
6602 6603
void OBSBasic::TogglePreview()
{
6604 6605
	previewEnabled = !previewEnabled;
	EnablePreviewDisplay(previewEnabled);
J
jp9000 已提交
6606
}
6607

6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625
void OBSBasic::EnablePreview()
{
	if (previewProgramMode)
		return;

	previewEnabled = true;
	EnablePreviewDisplay(true);
}

void OBSBasic::DisablePreview()
{
	if (previewProgramMode)
		return;

	previewEnabled = false;
	EnablePreviewDisplay(false);
}

J
jp9000 已提交
6626
static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
6627
{
J
jp9000 已提交
6628 6629
	if (obs_sceneitem_locked(item))
		return true;
6630

J
jp9000 已提交
6631
	struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
J
jp9000 已提交
6632
	struct vec2 pos;
6633

J
jp9000 已提交
6634
	if (!obs_sceneitem_selected(item)) {
J
jp9000 已提交
6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647
		if (obs_sceneitem_is_group(item)) {
			struct vec3 offset3;
			vec3_set(&offset3, offset.x, offset.y, 0.0f);

			struct matrix4 matrix;
			obs_sceneitem_get_draw_transform(item, &matrix);
			vec4_set(&matrix.t, 0.0f, 0.0f, 0.0f, 1.0f);
			matrix4_inv(&matrix, &matrix);
			vec3_transform(&offset3, &offset3, &matrix);

			struct vec2 new_offset;
			vec2_set(&new_offset, offset3.x, offset3.y);
			obs_sceneitem_group_enum_items(item, nudge_callback,
J
jp9000 已提交
6648
						       &new_offset);
J
jp9000 已提交
6649 6650
		}

J
jp9000 已提交
6651 6652
		return true;
	}
6653

J
jp9000 已提交
6654 6655 6656 6657 6658
	obs_sceneitem_get_pos(item, &pos);
	vec2_add(&pos, &pos, &offset);
	obs_sceneitem_set_pos(item, &pos);
	return true;
}
J
jp9000 已提交
6659

J
jp9000 已提交
6660 6661 6662 6663
void OBSBasic::Nudge(int dist, MoveDir dir)
{
	if (ui->preview->Locked())
		return;
6664

J
jp9000 已提交
6665 6666
	struct vec2 offset;
	vec2_set(&offset, 0.0f, 0.0f);
6667

J
jp9000 已提交
6668
	switch (dir) {
J
jp9000 已提交
6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680
	case MoveDir::Up:
		offset.y = (float)-dist;
		break;
	case MoveDir::Down:
		offset.y = (float)dist;
		break;
	case MoveDir::Left:
		offset.x = (float)-dist;
		break;
	case MoveDir::Right:
		offset.x = (float)dist;
		break;
J
jp9000 已提交
6681
	}
6682

J
jp9000 已提交
6683
	obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
6684 6685
}

J
jp9000 已提交
6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701
void OBSBasic::NudgeUp()
{
	Nudge(1, MoveDir::Up);
}
void OBSBasic::NudgeDown()
{
	Nudge(1, MoveDir::Down);
}
void OBSBasic::NudgeLeft()
{
	Nudge(1, MoveDir::Left);
}
void OBSBasic::NudgeRight()
{
	Nudge(1, MoveDir::Right);
}
J
jp9000 已提交
6702

6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713
void OBSBasic::DeleteProjector(OBSProjector *projector)
{
	for (size_t i = 0; i < projectors.size(); i++) {
		if (projectors[i] == projector) {
			projectors[i]->deleteLater();
			projectors.erase(projectors.begin() + i);
			break;
		}
	}
}

S
Shaolin 已提交
6714
OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
6715
				      ProjectorType type)
J
jp9000 已提交
6716 6717
{
	/* seriously?  10 monitors? */
C
cg2121 已提交
6718
	if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
S
Shaolin 已提交
6719
		return nullptr;
C
cg2121 已提交
6720

J
jp9000 已提交
6721
	OBSProjector *projector =
6722
		new OBSProjector(nullptr, source, monitor, type);
C
cg2121 已提交
6723

6724 6725
	if (projector)
		projectors.emplace_back(projector);
S
Shaolin 已提交
6726 6727

	return projector;
J
jp9000 已提交
6728 6729
}

R
Ryan Foster 已提交
6730 6731 6732
void OBSBasic::OpenStudioProgramProjector()
{
	int monitor = sender()->property("monitor").toInt();
6733
	OpenProjector(nullptr, monitor, ProjectorType::StudioProgram);
R
Ryan Foster 已提交
6734 6735
}

J
jp9000 已提交
6736 6737 6738
void OBSBasic::OpenPreviewProjector()
{
	int monitor = sender()->property("monitor").toInt();
6739
	OpenProjector(nullptr, monitor, ProjectorType::Preview);
J
jp9000 已提交
6740 6741 6742 6743 6744 6745 6746 6747 6748
}

void OBSBasic::OpenSourceProjector()
{
	int monitor = sender()->property("monitor").toInt();
	OBSSceneItem item = GetCurrentSceneItem();
	if (!item)
		return;

6749
	OpenProjector(obs_sceneitem_get_source(item), monitor,
J
jp9000 已提交
6750
		      ProjectorType::Source);
J
jp9000 已提交
6751 6752
}

S
Shaolin 已提交
6753 6754 6755
void OBSBasic::OpenMultiviewProjector()
{
	int monitor = sender()->property("monitor").toInt();
6756
	OpenProjector(nullptr, monitor, ProjectorType::Multiview);
S
Shaolin 已提交
6757 6758
}

J
jp9000 已提交
6759 6760 6761 6762 6763 6764 6765
void OBSBasic::OpenSceneProjector()
{
	int monitor = sender()->property("monitor").toInt();
	OBSScene scene = GetCurrentScene();
	if (!scene)
		return;

6766
	OpenProjector(obs_scene_get_source(scene), monitor,
J
jp9000 已提交
6767
		      ProjectorType::Scene);
C
cg2121 已提交
6768 6769
}

R
Ryan Foster 已提交
6770 6771
void OBSBasic::OpenStudioProgramWindow()
{
6772
	OpenProjector(nullptr, -1, ProjectorType::StudioProgram);
R
Ryan Foster 已提交
6773 6774
}

C
cg2121 已提交
6775 6776
void OBSBasic::OpenPreviewWindow()
{
6777
	OpenProjector(nullptr, -1, ProjectorType::Preview);
C
cg2121 已提交
6778 6779 6780 6781 6782 6783 6784 6785 6786
}

void OBSBasic::OpenSourceWindow()
{
	OBSSceneItem item = GetCurrentSceneItem();
	if (!item)
		return;

	OBSSource source = obs_sceneitem_get_source(item);
S
Shaolin 已提交
6787

6788
	OpenProjector(obs_sceneitem_get_source(item), -1,
J
jp9000 已提交
6789
		      ProjectorType::Source);
C
cg2121 已提交
6790 6791
}

S
Shaolin 已提交
6792 6793
void OBSBasic::OpenMultiviewWindow()
{
6794
	OpenProjector(nullptr, -1, ProjectorType::Multiview);
S
Shaolin 已提交
6795 6796
}

C
cg2121 已提交
6797 6798 6799 6800 6801 6802 6803
void OBSBasic::OpenSceneWindow()
{
	OBSScene scene = GetCurrentScene();
	if (!scene)
		return;

	OBSSource source = obs_scene_get_source(scene);
S
Shaolin 已提交
6804

6805
	OpenProjector(obs_scene_get_source(scene), -1, ProjectorType::Scene);
J
jp9000 已提交
6806
}
6807

C
cg2121 已提交
6808 6809
void OBSBasic::OpenSavedProjectors()
{
6810
	for (SavedProjectorInfo *info : savedProjectorsArray) {
6811 6812 6813 6814 6815 6816 6817
		OpenSavedProjector(info);
	}
}

void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info)
{
	if (info) {
S
Shaolin 已提交
6818
		OBSProjector *projector = nullptr;
6819
		switch (info->type) {
S
Shaolin 已提交
6820
		case ProjectorType::Source:
6821
		case ProjectorType::Scene: {
J
jp9000 已提交
6822 6823
			OBSSource source =
				obs_get_source_by_name(info->name.c_str());
6824
			if (!source)
6825
				return;
C
cg2121 已提交
6826

6827
			projector = OpenProjector(source, info->monitor,
J
jp9000 已提交
6828
						  info->type);
6829 6830 6831

			obs_source_release(source);
			break;
S
Shaolin 已提交
6832
		}
6833
		default: {
S
Shaolin 已提交
6834
			projector = OpenProjector(nullptr, info->monitor,
6835
						  info->type);
6836 6837
			break;
		}
C
cg2121 已提交
6838
		}
S
Shaolin 已提交
6839

6840
		if (projector && !info->geometry.empty() && info->monitor < 0) {
S
Shaolin 已提交
6841
			QByteArray byteArray = QByteArray::fromBase64(
J
jp9000 已提交
6842
				QByteArray(info->geometry.c_str()));
S
Shaolin 已提交
6843
			projector->restoreGeometry(byteArray);
S
Shaolin 已提交
6844

S
Shaolin 已提交
6845 6846 6847
			if (!WindowPositionValid(projector->normalGeometry())) {
				QRect rect = App()->desktop()->geometry();
				projector->setGeometry(QStyle::alignedRect(
J
jp9000 已提交
6848 6849
					Qt::LeftToRight, Qt::AlignCenter,
					size(), rect));
C
cg2121 已提交
6850 6851 6852 6853 6854
			}
		}
	}
}

6855 6856
void OBSBasic::on_actionFullscreenInterface_triggered()
{
6857
	if (!isFullScreen())
6858 6859 6860 6861 6862
		showFullScreen();
	else
		showNormal();
}

6863 6864 6865 6866
void OBSBasic::UpdateTitleBar()
{
	stringstream name;

J
jp9000 已提交
6867 6868 6869 6870
	const char *profile =
		config_get_string(App()->GlobalConfig(), "Basic", "Profile");
	const char *sceneCollection = config_get_string(
		App()->GlobalConfig(), "Basic", "SceneCollection");
J
jp9000 已提交
6871

6872 6873 6874 6875 6876
	name << "OBS ";
	if (previewProgramMode)
		name << "Studio ";

	name << App()->GetVersionString();
6877 6878 6879
	if (App()->IsPortableMode())
		name << " - Portable Mode";

J
jp9000 已提交
6880
	name << " - " << Str("TitleBar.Profile") << ": " << profile;
J
jp9000 已提交
6881
	name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
6882 6883 6884

	setWindowTitle(QT_UTF8(name.str().c_str()));
}
J
jp9000 已提交
6885 6886 6887 6888

int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
{
	char profiles_path[512];
J
jp9000 已提交
6889 6890
	const char *profile =
		config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
J
jp9000 已提交
6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908
	int ret;

	if (!profile)
		return -1;
	if (!path)
		return -1;
	if (!file)
		file = "";

	ret = GetConfigPath(profiles_path, 512, "obs-studio/basic/profiles");
	if (ret <= 0)
		return ret;

	if (!*file)
		return snprintf(path, size, "%s/%s", profiles_path, profile);

	return snprintf(path, size, "%s/%s/%s", profiles_path, profile, file);
}
6909

J
jp9000 已提交
6910
void OBSBasic::on_resetUI_triggered()
6911
{
6912
	/* prune deleted extra docks */
J
jp9000 已提交
6913
	for (int i = extraDocks.size() - 1; i >= 0; i--) {
6914 6915 6916 6917 6918 6919 6920
		if (!extraDocks[i]) {
			extraDocks.removeAt(i);
		}
	}

	if (extraDocks.size()) {
		QMessageBox::StandardButton button = QMessageBox::question(
J
jp9000 已提交
6921 6922
			this, QTStr("ResetUIWarning.Title"),
			QTStr("ResetUIWarning.Text"));
6923 6924 6925 6926 6927 6928

		if (button == QMessageBox::No)
			return;
	}

	/* undock/hide/center extra docks */
J
jp9000 已提交
6929
	for (int i = extraDocks.size() - 1; i >= 0; i--) {
6930 6931 6932
		if (extraDocks[i]) {
			extraDocks[i]->setVisible(true);
			extraDocks[i]->setFloating(true);
J
jp9000 已提交
6933 6934 6935
			extraDocks[i]->move(frameGeometry().topLeft() +
					    rect().center() -
					    extraDocks[i]->rect().center());
6936 6937 6938 6939
			extraDocks[i]->setVisible(false);
		}
	}

J
jp9000 已提交
6940
	restoreState(startingDockLayout);
6941

6942
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
J
jp9000 已提交
6943 6944 6945 6946 6947 6948 6949 6950 6951 6952
	int cx = width();
	int cy = height();

	int cx22_5 = cx * 225 / 1000;
	int cx5 = cx * 5 / 100;

	cy = cy * 225 / 1000;

	int mixerSize = cx - (cx22_5 * 2 + cx5 * 2);

J
jp9000 已提交
6953 6954 6955
	QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
				   ui->mixerDock, ui->transitionsDock,
				   ui->controlsDock};
J
jp9000 已提交
6956

J
jp9000 已提交
6957
	QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx5};
J
jp9000 已提交
6958 6959 6960 6961 6962 6963

	ui->scenesDock->setVisible(true);
	ui->sourcesDock->setVisible(true);
	ui->mixerDock->setVisible(true);
	ui->transitionsDock->setVisible(true);
	ui->controlsDock->setVisible(true);
6964 6965
	statsDock->setVisible(false);
	statsDock->setFloating(true);
J
jp9000 已提交
6966 6967 6968

	resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
	resizeDocks(docks, sizes, Qt::Horizontal);
6969
#endif
J
jp9000 已提交
6970 6971 6972 6973
}

void OBSBasic::on_lockUI_toggled(bool lock)
{
J
jp9000 已提交
6974 6975 6976
	QDockWidget::DockWidgetFeatures features =
		lock ? QDockWidget::NoDockWidgetFeatures
		     : QDockWidget::AllDockWidgetFeatures;
J
jp9000 已提交
6977

6978 6979 6980 6981 6982 6983 6984 6985
	QDockWidget::DockWidgetFeatures mainFeatures = features;
	mainFeatures &= ~QDockWidget::QDockWidget::DockWidgetClosable;

	ui->scenesDock->setFeatures(mainFeatures);
	ui->sourcesDock->setFeatures(mainFeatures);
	ui->mixerDock->setFeatures(mainFeatures);
	ui->transitionsDock->setFeatures(mainFeatures);
	ui->controlsDock->setFeatures(mainFeatures);
6986
	statsDock->setFeatures(features);
6987

J
jp9000 已提交
6988
	for (int i = extraDocks.size() - 1; i >= 0; i--) {
6989 6990 6991 6992 6993 6994
		if (!extraDocks[i]) {
			extraDocks.removeAt(i);
		} else {
			extraDocks[i]->setFeatures(features);
		}
	}
6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009
}

void OBSBasic::on_toggleListboxToolbars_toggled(bool visible)
{
	ui->sourcesToolbar->setVisible(visible);
	ui->scenesToolbar->setVisible(visible);

	config_set_bool(App()->GlobalConfig(), "BasicWindow",
			"ShowListboxToolbars", visible);
}

void OBSBasic::on_toggleStatusBar_toggled(bool visible)
{
	ui->statusbar->setVisible(visible);

J
jp9000 已提交
7010 7011
	config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
			visible);
7012
}
J
jp9000 已提交
7013

7014 7015 7016
void OBSBasic::on_toggleSourceIcons_toggled(bool visible)
{
	ui->sources->SetIconsVisible(visible);
7017 7018
	if (advAudioWindow != nullptr)
		advAudioWindow->SetIconsVisible(visible);
7019 7020 7021 7022 7023

	config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowSourceIcons",
			visible);
}

J
jp9000 已提交
7024 7025 7026 7027 7028
void OBSBasic::on_actionLockPreview_triggered()
{
	ui->preview->ToggleLocked();
	ui->actionLockPreview->setChecked(ui->preview->Locked());
}
C
cg2121 已提交
7029

J
Joseph El-Khouri 已提交
7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045
void OBSBasic::on_scalingMenu_aboutToShow()
{
	obs_video_info ovi;
	obs_get_video_info(&ovi);

	QAction *action = ui->actionScaleCanvas;
	QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas");
	text = text.arg(QString::number(ovi.base_width),
			QString::number(ovi.base_height));
	action->setText(text);

	action = ui->actionScaleOutput;
	text = QTStr("Basic.MainMenu.Edit.Scale.Output");
	text = text.arg(QString::number(ovi.output_width),
			QString::number(ovi.output_height));
	action->setText(text);
7046
	action->setVisible(!(ovi.output_width == ovi.base_width &&
J
jp9000 已提交
7047
			     ovi.output_height == ovi.base_height));
J
Joseph El-Khouri 已提交
7048 7049 7050 7051 7052 7053

	UpdatePreviewScalingMenu();
}

void OBSBasic::on_actionScaleWindow_triggered()
{
7054
	ui->preview->SetFixedScaling(false);
J
Joseph El-Khouri 已提交
7055 7056 7057 7058 7059 7060
	ui->preview->ResetScrollingOffset();
	emit ui->preview->DisplayResized();
}

void OBSBasic::on_actionScaleCanvas_triggered()
{
7061 7062
	ui->preview->SetFixedScaling(true);
	ui->preview->SetScalingLevel(0);
J
Joseph El-Khouri 已提交
7063 7064 7065 7066 7067
	emit ui->preview->DisplayResized();
}

void OBSBasic::on_actionScaleOutput_triggered()
{
7068 7069 7070 7071 7072 7073
	obs_video_info ovi;
	obs_get_video_info(&ovi);

	ui->preview->SetFixedScaling(true);
	float scalingAmount = float(ovi.output_width) / float(ovi.base_width);
	// log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY)
J
jp9000 已提交
7074 7075
	int32_t approxScalingLevel =
		int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
7076 7077
	ui->preview->SetScalingLevel(approxScalingLevel);
	ui->preview->SetScalingAmount(scalingAmount);
J
Joseph El-Khouri 已提交
7078 7079 7080
	emit ui->preview->DisplayResized();
}

C
cg2121 已提交
7081 7082 7083
void OBSBasic::SetShowing(bool showing)
{
	if (!showing && isVisible()) {
J
jp9000 已提交
7084 7085 7086
		config_set_string(App()->GlobalConfig(), "BasicWindow",
				  "geometry",
				  saveGeometry().toBase64().constData());
C
cg2121 已提交
7087

7088 7089 7090 7091 7092 7093 7094 7095 7096
		/* hide all visible child dialogs */
		visDlgPositions.clear();
		if (!visDialogs.isEmpty()) {
			for (QDialog *dlg : visDialogs) {
				visDlgPositions.append(dlg->pos());
				dlg->hide();
			}
		}

7097 7098
		if (showHide)
			showHide->setText(QTStr("Basic.SystemTray.Show"));
C
cg2121 已提交
7099 7100 7101 7102
		QTimer::singleShot(250, this, SLOT(hide()));

		setVisible(false);

7103 7104 7105 7106
#ifdef __APPLE__
		EnableOSXDockIcon(false);
#endif

C
cg2121 已提交
7107
	} else if (showing && !isVisible()) {
7108 7109
		if (showHide)
			showHide->setText(QTStr("Basic.SystemTray.Hide"));
C
cg2121 已提交
7110 7111 7112
		QTimer::singleShot(250, this, SLOT(show()));

		setVisible(true);
7113

7114 7115 7116 7117 7118 7119 7120 7121
#ifdef __APPLE__
		EnableOSXDockIcon(true);
#endif

		/* raise and activate window to ensure it is on top */
		raise();
		activateWindow();

7122 7123 7124 7125 7126 7127 7128 7129 7130
		/* show all child dialogs that was visible earlier */
		if (!visDialogs.isEmpty()) {
			for (int i = 0; i < visDialogs.size(); ++i) {
				QDialog *dlg = visDialogs[i];
				dlg->move(visDlgPositions[i]);
				dlg->show();
			}
		}

7131 7132 7133 7134
		/* Unminimize window if it was hidden to tray instead of task
		 * bar. */
		if (sysTrayMinimizeToTray()) {
			Qt::WindowStates state;
J
jp9000 已提交
7135
			state = windowState() & ~Qt::WindowMinimized;
7136 7137 7138
			state |= Qt::WindowActive;
			setWindowState(state);
		}
C
cg2121 已提交
7139 7140 7141
	}
}

7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153
void OBSBasic::ToggleShowHide()
{
	bool showing = isVisible();
	if (showing) {
		/* check for modal dialogs */
		EnumDialogs();
		if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
			return;
	}
	SetShowing(!showing);
}

7154 7155
void OBSBasic::SystemTrayInit()
{
J
jp9000 已提交
7156 7157 7158
	trayIcon.reset(new QSystemTrayIcon(
		QIcon::fromTheme("obs-tray", QIcon(":/res/images/obs.png")),
		this));
C
cg2121 已提交
7159 7160
	trayIcon->setToolTip("OBS Studio");

J
jp9000 已提交
7161
	showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
C
cg2121 已提交
7162
	sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
J
jp9000 已提交
7163
				    trayIcon.data());
C
cg2121 已提交
7164
	sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
J
jp9000 已提交
7165
				    trayIcon.data());
J
jp9000 已提交
7166
	sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
J
jp9000 已提交
7167 7168
					  trayIcon.data());
	exit = new QAction(QTStr("Exit"), trayIcon.data());
C
cg2121 已提交
7169

7170 7171 7172
	trayMenu = new QMenu;
	previewProjector = new QMenu(QTStr("PreviewProjector"));
	studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
7173
	AddProjectorMenuMonitors(previewProjector, this,
J
jp9000 已提交
7174
				 SLOT(OpenPreviewProjector()));
7175
	AddProjectorMenuMonitors(studioProgramProjector, this,
J
jp9000 已提交
7176
				 SLOT(OpenStudioProgramProjector()));
7177 7178 7179 7180 7181 7182 7183 7184
	trayMenu->addAction(showHide);
	trayMenu->addMenu(previewProjector);
	trayMenu->addMenu(studioProgramProjector);
	trayMenu->addAction(sysTrayStream);
	trayMenu->addAction(sysTrayRecord);
	trayMenu->addAction(sysTrayReplayBuffer);
	trayMenu->addAction(exit);
	trayIcon->setContextMenu(trayMenu);
7185
	trayIcon->show();
7186

J
jp9000 已提交
7187 7188
	if (outputHandler && !outputHandler->replayBuffer)
		sysTrayReplayBuffer->setEnabled(false);
7189

7190
	connect(trayIcon.data(),
J
jp9000 已提交
7191 7192 7193 7194 7195 7196 7197 7198 7199 7200
		SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this,
		SLOT(IconActivated(QSystemTrayIcon::ActivationReason)));
	connect(showHide, SIGNAL(triggered()), this, SLOT(ToggleShowHide()));
	connect(sysTrayStream, SIGNAL(triggered()), this,
		SLOT(on_streamButton_clicked()));
	connect(sysTrayRecord, SIGNAL(triggered()), this,
		SLOT(on_recordButton_clicked()));
	connect(sysTrayReplayBuffer.data(), &QAction::triggered, this,
		&OBSBasic::ReplayBufferClicked);
	connect(exit, SIGNAL(triggered()), this, SLOT(close()));
C
cg2121 已提交
7201 7202 7203 7204
}

void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
{
7205 7206 7207 7208 7209 7210 7211 7212
	// Refresh projector list
	previewProjector->clear();
	studioProgramProjector->clear();
	AddProjectorMenuMonitors(previewProjector, this,
				 SLOT(OpenPreviewProjector()));
	AddProjectorMenuMonitors(studioProgramProjector, this,
				 SLOT(OpenStudioProgramProjector()));

7213 7214
	if (reason == QSystemTrayIcon::Trigger) {
		EnablePreviewDisplay(previewEnabled && !isVisible());
C
cg2121 已提交
7215
		ToggleShowHide();
7216
	}
C
cg2121 已提交
7217 7218 7219
}

void OBSBasic::SysTrayNotify(const QString &text,
J
jp9000 已提交
7220
			     QSystemTrayIcon::MessageIcon n)
C
cg2121 已提交
7221
{
7222
	if (trayIcon && QSystemTrayIcon::supportsMessages()) {
C
cg2121 已提交
7223
		QSystemTrayIcon::MessageIcon icon =
J
jp9000 已提交
7224
			QSystemTrayIcon::MessageIcon(n);
C
cg2121 已提交
7225 7226 7227 7228 7229 7230 7231 7232
		trayIcon->showMessage("OBS Studio", text, icon, 10000);
	}
}

void OBSBasic::SystemTray(bool firstStarted)
{
	if (!QSystemTrayIcon::isSystemTrayAvailable())
		return;
7233
	if (!trayIcon && !firstStarted)
J
jp9000 已提交
7234
		return;
C
cg2121 已提交
7235

J
jp9000 已提交
7236 7237 7238 7239
	bool sysTrayWhenStarted = config_get_bool(
		GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
	bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
					      "SysTrayEnabled");
C
cg2121 已提交
7240 7241 7242 7243 7244 7245

	if (firstStarted)
		SystemTrayInit();

	if (!sysTrayWhenStarted && !sysTrayEnabled) {
		trayIcon->hide();
J
jp9000 已提交
7246 7247
	} else if ((sysTrayWhenStarted && sysTrayEnabled) ||
		   opt_minimize_tray) {
C
cg2121 已提交
7248 7249 7250 7251 7252
		trayIcon->show();
		if (firstStarted) {
			QTimer::singleShot(50, this, SLOT(hide()));
			EnablePreviewDisplay(false);
			setVisible(false);
7253 7254 7255
#ifdef __APPLE__
			EnableOSXDockIcon(false);
#endif
C
cg2121 已提交
7256
			opt_minimize_tray = false;
C
cg2121 已提交
7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270
		}
	} else if (sysTrayEnabled) {
		trayIcon->show();
	} else if (!sysTrayEnabled) {
		trayIcon->hide();
	} else if (!sysTrayWhenStarted && sysTrayEnabled) {
		trayIcon->hide();
	}

	if (isVisible())
		showHide->setText(QTStr("Basic.SystemTray.Hide"));
	else
		showHide->setText(QTStr("Basic.SystemTray.Show"));
}
7271 7272 7273

bool OBSBasic::sysTrayMinimizeToTray()
{
J
jp9000 已提交
7274 7275
	return config_get_bool(GetGlobalConfig(), "BasicWindow",
			       "SysTrayMinimizeToTray");
7276
}
7277 7278 7279

void OBSBasic::on_actionCopySource_triggered()
{
7280 7281
	copyStrings.clear();
	bool allowPastingDuplicate = true;
J
jp9000 已提交
7282

7283 7284 7285 7286
	for (auto &selectedSource : GetAllSelectedSourceItems()) {
		OBSSceneItem item = ui->sources->Get(selectedSource.row());
		if (!item)
			continue;
7287

7288
		on_actionCopyTransform_triggered();
7289

7290
		OBSSource source = obs_sceneitem_get_source(item);
7291

7292
		copyStrings.push_front(obs_source_get_name(source));
7293

7294 7295 7296
		copyVisible = obs_sceneitem_visible(item);

		uint32_t output_flags = obs_source_get_output_flags(source);
7297
		if (output_flags & OBS_SOURCE_DO_NOT_DUPLICATE)
7298 7299 7300 7301 7302
			allowPastingDuplicate = false;
	}

	ui->actionPasteRef->setEnabled(true);
	ui->actionPasteDup->setEnabled(allowPastingDuplicate);
7303 7304 7305 7306
}

void OBSBasic::on_actionPasteRef_triggered()
{
7307 7308 7309 7310 7311
	for (auto &copyString : copyStrings) {
		/* do not allow duplicate refs of the same group in the same scene */
		OBSScene scene = GetCurrentScene();
		if (!!obs_scene_get_group(scene, copyString))
			continue;
J
jp9000 已提交
7312

7313 7314 7315 7316
		OBSBasicSourceSelect::SourcePaste(copyString, copyVisible,
						  false);
		on_actionPasteTransform_triggered();
	}
7317 7318 7319 7320
}

void OBSBasic::on_actionPasteDup_triggered()
{
7321 7322 7323 7324 7325
	for (auto &copyString : copyStrings) {
		OBSBasicSourceSelect::SourcePaste(copyString, copyVisible,
						  true);
		on_actionPasteTransform_triggered();
	}
7326 7327
}

7328 7329
void OBSBasic::AudioMixerCopyFilters()
{
J
jp9000 已提交
7330 7331
	QAction *action = reinterpret_cast<QAction *>(sender());
	VolControl *vol = action->property("volControl").value<VolControl *>();
7332 7333 7334 7335 7336 7337 7338
	obs_source_t *source = vol->GetSource();

	copyFiltersString = obs_source_get_name(source);
}

void OBSBasic::AudioMixerPasteFilters()
{
J
jp9000 已提交
7339 7340
	QAction *action = reinterpret_cast<QAction *>(sender());
	VolControl *vol = action->property("volControl").value<VolControl *>();
7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351
	obs_source_t *dstSource = vol->GetSource();

	OBSSource source = obs_get_source_by_name(copyFiltersString);
	obs_source_release(source);

	if (source == dstSource)
		return;

	obs_source_copy_filters(dstSource, source);
}

7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369
void OBSBasic::SceneCopyFilters()
{
	copyFiltersString = obs_source_get_name(GetCurrentSceneSource());
}

void OBSBasic::ScenePasteFilters()
{
	OBSSource source = obs_get_source_by_name(copyFiltersString);
	obs_source_release(source);

	OBSSource dstSource = GetCurrentSceneSource();

	if (source == dstSource)
		return;

	obs_source_copy_filters(dstSource, source);
}

7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386
void OBSBasic::on_actionCopyFilters_triggered()
{
	OBSSceneItem item = GetCurrentSceneItem();

	if (!item)
		return;

	OBSSource source = obs_sceneitem_get_source(item);

	copyFiltersString = obs_source_get_name(source);

	ui->actionPasteFilters->setEnabled(true);
}

void OBSBasic::on_actionPasteFilters_triggered()
{
	OBSSource source = obs_get_source_by_name(copyFiltersString);
7387
	obs_source_release(source);
7388

7389
	OBSSceneItem sceneItem = GetCurrentSceneItem();
7390 7391 7392 7393 7394 7395 7396
	OBSSource dstSource = obs_sceneitem_get_source(sceneItem);

	if (source == dstSource)
		return;

	obs_source_copy_filters(dstSource, source);
}
J
jp9000 已提交
7397

7398
static void ConfirmColor(SourceTree *sources, const QColor &color,
J
jp9000 已提交
7399
			 QModelIndexList selectedItems)
7400 7401
{
	for (int x = 0; x < selectedItems.count(); x++) {
J
jp9000 已提交
7402 7403 7404 7405
		SourceTreeItem *treeItem =
			sources->GetItemWidget(selectedItems[x].row());
		treeItem->setStyleSheet("background: " +
					color.name(QColor::HexArgb));
7406 7407 7408
		treeItem->style()->unpolish(treeItem);
		treeItem->style()->polish(treeItem);

J
jp9000 已提交
7409
		OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
7410 7411 7412 7413
		obs_data_t *privData =
			obs_sceneitem_get_private_settings(sceneItem);
		obs_data_set_int(privData, "color-preset", 1);
		obs_data_set_string(privData, "color",
J
jp9000 已提交
7414
				    QT_TO_UTF8(color.name(QColor::HexArgb)));
7415 7416 7417 7418 7419 7420 7421 7422
		obs_data_release(privData);
	}
}

void OBSBasic::ColorChange()
{
	QModelIndexList selectedItems =
		ui->sources->selectionModel()->selectedIndexes();
J
jp9000 已提交
7423 7424
	QAction *action = qobject_cast<QAction *>(sender());
	QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
7425 7426 7427 7428 7429 7430 7431 7432

	if (selectedItems.count() == 0)
		return;

	if (colorButton) {
		int preset = colorButton->property("bgColor").value<int>();

		for (int x = 0; x < selectedItems.count(); x++) {
J
jp9000 已提交
7433 7434
			SourceTreeItem *treeItem = ui->sources->GetItemWidget(
				selectedItems[x].row());
7435 7436 7437 7438 7439
			treeItem->setStyleSheet("");
			treeItem->setProperty("bgColor", preset);
			treeItem->style()->unpolish(treeItem);
			treeItem->style()->polish(treeItem);

J
jp9000 已提交
7440 7441
			OBSSceneItem sceneItem =
				ui->sources->Get(selectedItems[x].row());
7442 7443 7444 7445 7446 7447 7448 7449 7450 7451
			obs_data_t *privData =
				obs_sceneitem_get_private_settings(sceneItem);
			obs_data_set_int(privData, "color-preset", preset + 1);
			obs_data_set_string(privData, "color", "");
			obs_data_release(privData);
		}

		for (int i = 1; i < 9; i++) {
			stringstream button;
			button << "preset" << i;
J
jp9000 已提交
7452 7453 7454 7455
			QPushButton *cButton =
				colorButton->parentWidget()
					->findChild<QPushButton *>(
						button.str().c_str());
7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467
			cButton->setStyleSheet("border: 1px solid black");
		}

		colorButton->setStyleSheet("border: 2px solid black");
	} else if (action) {
		int preset = action->property("bgColor").value<int>();

		if (preset == 1) {
			OBSSceneItem curSceneItem = GetCurrentSceneItem();
			SourceTreeItem *curTreeItem =
				GetItemWidgetFromSceneItem(curSceneItem);
			obs_data_t *curPrivData =
J
jp9000 已提交
7468 7469
				obs_sceneitem_get_private_settings(
					curSceneItem);
7470

J
jp9000 已提交
7471 7472
			int oldPreset =
				obs_data_get_int(curPrivData, "color-preset");
7473 7474 7475 7476 7477
			const QString oldSheet = curTreeItem->styleSheet();

			auto liveChangeColor = [=](const QColor &color) {
				if (color.isValid()) {
					curTreeItem->setStyleSheet(
J
jp9000 已提交
7478 7479
						"background: " +
						color.name(QColor::HexArgb));
7480 7481 7482 7483 7484 7485
				}
			};

			auto changedColor = [=](const QColor &color) {
				if (color.isValid()) {
					ConfirmColor(ui->sources, color,
J
jp9000 已提交
7486
						     selectedItems);
7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500
				}
			};

			auto rejected = [=]() {
				if (oldPreset == 1) {
					curTreeItem->setStyleSheet(oldSheet);
					curTreeItem->setProperty("bgColor", 0);
				} else if (oldPreset == 0) {
					curTreeItem->setStyleSheet(
						"background: none");
					curTreeItem->setProperty("bgColor", 0);
				} else {
					curTreeItem->setStyleSheet("");
					curTreeItem->setProperty("bgColor",
J
jp9000 已提交
7501
								 oldPreset - 1);
7502 7503 7504 7505 7506 7507 7508 7509 7510
				}

				curTreeItem->style()->unpolish(curTreeItem);
				curTreeItem->style()->polish(curTreeItem);
			};

			QColorDialog::ColorDialogOptions options =
				QColorDialog::ShowAlphaChannel;

J
jp9000 已提交
7511 7512
			const char *oldColor =
				obs_data_get_string(curPrivData, "color");
7513
			const char *customColor = *oldColor != 0 ? oldColor
J
jp9000 已提交
7514
								 : "#55FF0000";
7515
#ifndef _WIN32
7516 7517 7518 7519 7520
			options |= QColorDialog::DontUseNativeDialog;
#endif

			QColorDialog *colorDialog = new QColorDialog(this);
			colorDialog->setOptions(options);
J
jp9000 已提交
7521
			colorDialog->setCurrentColor(QColor(customColor));
7522
			connect(colorDialog, &QColorDialog::currentColorChanged,
J
jp9000 已提交
7523
				liveChangeColor);
7524
			connect(colorDialog, &QColorDialog::colorSelected,
J
jp9000 已提交
7525 7526
				changedColor);
			connect(colorDialog, &QColorDialog::rejected, rejected);
7527 7528 7529 7530 7531
			colorDialog->open();

			obs_data_release(curPrivData);
		} else {
			for (int x = 0; x < selectedItems.count(); x++) {
J
jp9000 已提交
7532 7533 7534
				SourceTreeItem *treeItem =
					ui->sources->GetItemWidget(
						selectedItems[x].row());
7535 7536 7537 7538 7539 7540 7541 7542 7543 7544 7545
				treeItem->setStyleSheet("background: none");
				treeItem->setProperty("bgColor", preset);
				treeItem->style()->unpolish(treeItem);
				treeItem->style()->polish(treeItem);

				OBSSceneItem sceneItem = ui->sources->Get(
					selectedItems[x].row());
				obs_data_t *privData =
					obs_sceneitem_get_private_settings(
						sceneItem);
				obs_data_set_int(privData, "color-preset",
J
jp9000 已提交
7546
						 preset);
7547 7548 7549 7550 7551 7552 7553
				obs_data_set_string(privData, "color", "");
				obs_data_release(privData);
			}
		}
	}
}

J
jp9000 已提交
7554
SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
7555 7556 7557 7558 7559 7560 7561 7562 7563 7564
{
	int i = 0;
	SourceTreeItem *treeItem = ui->sources->GetItemWidget(i);
	OBSSceneItem item = ui->sources->Get(i);
	int64_t id = obs_sceneitem_get_id(sceneItem);
	while (treeItem && obs_sceneitem_get_id(item) != id) {
		i++;
		treeItem = ui->sources->GetItemWidget(i);
		item = ui->sources->Get(i);
	}
J
jp9000 已提交
7565
	if (treeItem)
7566 7567 7568 7569 7570
		return treeItem;

	return nullptr;
}

J
jp9000 已提交
7571 7572 7573 7574 7575 7576 7577
void OBSBasic::on_autoConfigure_triggered()
{
	AutoConfig test(this);
	test.setModal(true);
	test.show();
	test.exec();
}
J
jp9000 已提交
7578 7579 7580

void OBSBasic::on_stats_triggered()
{
7581 7582 7583 7584 7585 7586
	if (!stats.isNull()) {
		stats->show();
		stats->raise();
		return;
	}

J
jp9000 已提交
7587 7588 7589 7590 7591
	OBSBasicStats *statsDlg;
	statsDlg = new OBSBasicStats(nullptr);
	statsDlg->show();
	stats = statsDlg;
}
7592

C
cg2121 已提交
7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603
void OBSBasic::on_actionShowAbout_triggered()
{
	if (about)
		about->close();

	about = new OBSAbout(this);
	about->show();

	about->setAttribute(Qt::WA_DeleteOnClose, true);
}

7604 7605
void OBSBasic::ResizeOutputSizeOfSource()
{
7606
	if (obs_video_active())
7607 7608 7609
		return;

	QMessageBox resize_output(this);
J
jp9000 已提交
7610 7611 7612 7613
	resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") + "\n\n" +
			      QTStr("ResizeOutputSizeOfSource.Continue"));
	QAbstractButton *Yes =
		resize_output.addButton(QTStr("Yes"), QMessageBox::YesRole);
7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634
	resize_output.addButton(QTStr("No"), QMessageBox::NoRole);
	resize_output.setIcon(QMessageBox::Warning);
	resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource"));
	resize_output.exec();

	if (resize_output.clickedButton() != Yes)
		return;

	OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem());

	int width = obs_source_get_width(source);
	int height = obs_source_get_height(source);

	config_set_uint(basicConfig, "Video", "BaseCX", width);
	config_set_uint(basicConfig, "Video", "BaseCY", height);
	config_set_uint(basicConfig, "Video", "OutputCX", width);
	config_set_uint(basicConfig, "Video", "OutputCY", height);

	ResetVideo();
	on_actionFitToScreen_triggered();
}
7635

7636 7637 7638 7639 7640 7641 7642 7643
QAction *OBSBasic::AddDockWidget(QDockWidget *dock)
{
	QAction *action = ui->viewMenuDocks->addAction(dock->windowTitle());
	action->setCheckable(true);
	assignDockToggle(dock, action);
	extraDocks.push_back(dock);

	bool lock = ui->lockUI->isChecked();
J
jp9000 已提交
7644 7645 7646
	QDockWidget::DockWidgetFeatures features =
		lock ? QDockWidget::NoDockWidgetFeatures
		     : QDockWidget::AllDockWidgetFeatures;
7647 7648 7649 7650

	dock->setFeatures(features);

	/* prune deleted docks */
J
jp9000 已提交
7651
	for (int i = extraDocks.size() - 1; i >= 0; i--) {
7652 7653 7654 7655 7656 7657 7658 7659
		if (!extraDocks[i]) {
			extraDocks.removeAt(i);
		}
	}

	return action;
}

7660 7661
OBSBasic *OBSBasic::Get()
{
J
jp9000 已提交
7662
	return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
7663
}
7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684

bool OBSBasic::StreamingActive()
{
	if (!outputHandler)
		return false;
	return outputHandler->StreamingActive();
}

bool OBSBasic::RecordingActive()
{
	if (!outputHandler)
		return false;
	return outputHandler->RecordingActive();
}

bool OBSBasic::ReplayBufferActive()
{
	if (!outputHandler)
		return false;
	return outputHandler->ReplayBufferActive();
}
7685 7686 7687 7688 7689 7690 7691

SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
	: QStyledItemDelegate(parent)
{
}

void SceneRenameDelegate::setEditorData(QWidget *editor,
J
jp9000 已提交
7692
					const QModelIndex &index) const
7693 7694
{
	QStyledItemDelegate::setEditorData(editor, index);
J
jp9000 已提交
7695
	QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
7696 7697 7698
	if (lineEdit)
		lineEdit->selectAll();
}
7699 7700 7701 7702 7703 7704

bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event)
{
	if (event->type() == QEvent::KeyPress) {
		QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
		if (keyEvent->key() == Qt::Key_Escape) {
J
jp9000 已提交
7705
			QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
7706 7707 7708 7709 7710 7711 7712
			if (lineEdit)
				lineEdit->undo();
		}
	}

	return QStyledItemDelegate::eventFilter(editor, event);
}
7713 7714 7715 7716 7717 7718 7719 7720

void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
{
	if (!error.isEmpty())
		return;

	patronJson = QT_TO_UTF8(text);
}
J
jp9000 已提交
7721 7722 7723 7724 7725 7726 7727 7728 7729

void OBSBasic::PauseRecording()
{
	if (!pause || !outputHandler || !outputHandler->fileOutput)
		return;

	obs_output_t *output = outputHandler->fileOutput;

	if (obs_output_pause(output, true)) {
7730 7731
		pause->setAccessibleName(QTStr("Basic.Main.UnpauseRecording"));
		pause->setToolTip(QTStr("Basic.Main.UnpauseRecording"));
7732
		pause->blockSignals(true);
J
jp9000 已提交
7733
		pause->setChecked(true);
7734
		pause->blockSignals(false);
7735

7736 7737
		ui->statusbar->RecordingPaused();

7738 7739 7740 7741 7742
#ifdef _WIN32
		taskProg->pause();
		taskBtn->setOverlayIcon(QIcon::fromTheme(
			"obs-paused", QIcon(":/res/images/paused.png")));
#endif
7743 7744 7745
		if (trayIcon)
			trayIcon->setIcon(QIcon(":/res/images/obs_paused.png"));

J
jp9000 已提交
7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763
		os_atomic_set_bool(&recording_paused, true);

		if (api)
			api->on_event(OBS_FRONTEND_EVENT_RECORDING_PAUSED);

		if (os_atomic_load_bool(&replaybuf_active))
			ShowReplayBufferPauseWarning();
	}
}

void OBSBasic::UnpauseRecording()
{
	if (!pause || !outputHandler || !outputHandler->fileOutput)
		return;

	obs_output_t *output = outputHandler->fileOutput;

	if (obs_output_pause(output, false)) {
7764 7765
		pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
		pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
7766
		pause->blockSignals(true);
J
jp9000 已提交
7767
		pause->setChecked(false);
7768
		pause->blockSignals(false);
7769

7770 7771
		ui->statusbar->RecordingUnpaused();

7772 7773 7774 7775 7776
#ifdef _WIN32
		taskProg->resume();
		taskBtn->setOverlayIcon(QIcon::fromTheme(
			"obs-active", QIcon(":/res/images/active.png")));
#endif
7777 7778 7779 7780
		if (trayIcon)
			trayIcon->setIcon(
				QIcon(":/res/images/tray_active.png"));

J
jp9000 已提交
7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795
		os_atomic_set_bool(&recording_paused, false);

		if (api)
			api->on_event(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED);
	}
}

void OBSBasic::PauseToggled()
{
	if (!pause || !outputHandler || !outputHandler->fileOutput)
		return;

	obs_output_t *output = outputHandler->fileOutput;
	bool enable = !obs_output_paused(output);

7796 7797 7798 7799
	if (enable)
		PauseRecording();
	else
		UnpauseRecording();
J
jp9000 已提交
7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838
}

void OBSBasic::UpdatePause(bool activate)
{
	if (!activate || !outputHandler || !outputHandler->RecordingActive()) {
		pause.reset();
		return;
	}

	const char *mode = config_get_string(basicConfig, "Output", "Mode");
	bool adv = astrcmpi(mode, "Advanced") == 0;
	bool shared;

	if (adv) {
		const char *recType =
			config_get_string(basicConfig, "AdvOut", "RecType");

		if (astrcmpi(recType, "FFmpeg") == 0) {
			shared = config_get_bool(basicConfig, "AdvOut",
						 "FFOutputToFile");
		} else {
			const char *recordEncoder = config_get_string(
				basicConfig, "AdvOut", "RecEncoder");
			shared = astrcmpi(recordEncoder, "none") == 0;
		}
	} else {
		const char *quality = config_get_string(
			basicConfig, "SimpleOutput", "RecQuality");
		shared = strcmp(quality, "Stream") == 0;
	}

	if (!shared) {
		pause.reset(new QPushButton());
		pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
		pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
		pause->setCheckable(true);
		pause->setChecked(false);
		pause->setProperty("themeID",
				   QVariant(QStringLiteral("pauseIconSmall")));
7839
		connect(pause.data(), &QAbstractButton::clicked, this,
J
jp9000 已提交
7840 7841 7842 7843 7844 7845
			&OBSBasic::PauseToggled);
		ui->recordingLayout->addWidget(pause.data());
	} else {
		pause.reset();
	}
}
7846

7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866
void OBSBasic::UpdateReplayBuffer(bool activate)
{
	if (!activate || !outputHandler ||
	    !outputHandler->ReplayBufferActive()) {
		replay.reset();
		return;
	}

	replay.reset(new QPushButton());
	replay->setAccessibleName(QTStr("Basic.Main.SaveReplay"));
	replay->setToolTip(QTStr("Basic.Main.SaveReplay"));
	replay->setCheckable(true);
	replay->setChecked(false);
	replay->setProperty("themeID",
			    QVariant(QStringLiteral("replayIconSmall")));
	connect(replay.data(), &QAbstractButton::clicked, this,
		&OBSBasic::ReplayBufferSave);
	replayLayout->addWidget(replay.data());
}

7867 7868 7869 7870
#define MBYTE (1024ULL * 1024ULL)
#define MBYTES_LEFT_STOP_REC 50ULL
#define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)

7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893
const char *OBSBasic::GetCurrentOutputPath()
{
	const char *path = nullptr;
	const char *mode = config_get_string(Config(), "Output", "Mode");

	if (strcmp(mode, "Advanced") == 0) {
		const char *advanced_mode =
			config_get_string(Config(), "AdvOut", "RecType");

		if (strcmp(advanced_mode, "FFmpeg") == 0) {
			path = config_get_string(Config(), "AdvOut",
						 "FFFilePath");
		} else {
			path = config_get_string(Config(), "AdvOut",
						 "RecFilePath");
		}
	} else {
		path = config_get_string(Config(), "SimpleOutput", "FilePath");
	}

	return path;
}

7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906 7907
void OBSBasic::OutputPathInvalidMessage()
{
	blog(LOG_ERROR, "Recording stopped because of bad output path");

	OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"),
				QTStr("Output.BadPath.Text"));
}

bool OBSBasic::OutputPathValid()
{
	const char *path = GetCurrentOutputPath();
	return path && *path && QDir(path).exists();
}

7908 7909 7910 7911 7912 7913 7914 7915 7916 7917
void OBSBasic::DiskSpaceMessage()
{
	blog(LOG_ERROR, "Recording stopped because of low disk space");

	OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"),
				QTStr("Output.RecordNoSpace.Msg"));
}

bool OBSBasic::LowDiskSpace()
{
7918 7919 7920 7921 7922
	const char *path;

	path = GetCurrentOutputPath();
	if (!path)
		return false;
7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940

	uint64_t num_bytes = os_get_free_disk_space(path);

	if (num_bytes < (MAX_BYTES_LEFT))
		return true;
	else
		return false;
}

void OBSBasic::CheckDiskSpaceRemaining()
{
	if (LowDiskSpace()) {
		StopRecording();
		StopReplayBuffer();

		DiskSpaceMessage();
	}
}
7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952

void OBSBasic::ScenesReordered(const QModelIndex &parent, int start, int end,
			       const QModelIndex &destination, int row)
{
	UNUSED_PARAMETER(parent);
	UNUSED_PARAMETER(start);
	UNUSED_PARAMETER(end);
	UNUSED_PARAMETER(destination);
	UNUSED_PARAMETER(row);

	OBSProjector::UpdateMultiviewProjectors();
}
C
Clayton Groeneveld 已提交
7953 7954 7955 7956 7957 7958 7959

void OBSBasic::ResetStatsHotkey()
{
	QList<OBSBasicStats *> list = findChildren<OBSBasicStats *>();

	foreach(OBSBasicStats * s, list) s->Reset();
}
7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970

void OBSBasic::on_customContextMenuRequested(const QPoint &pos)
{
	QWidget *widget = childAt(pos);
	const char *className = nullptr;
	if (widget != nullptr)
		className = widget->metaObject()->className();

	if (!className || strstr(className, "Dock") != nullptr)
		ui->viewMenuDocks->exec(mapToGlobal(pos));
}