window-basic-main.cpp 205.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

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

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

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

J
jp9000 已提交
65
#include "ui_OBSBasic.h"
66
#include "ui_ColorSelect.h"
67

J
jp9000 已提交
68
#include <fstream>
69 70
#include <sstream>

71 72 73
#include <QScreen>
#include <QWindow>

J
jp9000 已提交
74 75 76
#include <json11.hpp>

using namespace json11;
77
using namespace std;
J
jp9000 已提交
78

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

J
jp9000 已提交
83 84
#include "ui-config.h"

J
jp9000 已提交
85
struct QCef;
86 87
struct QCefCookieManager;

J
jp9000 已提交
88
QCef *cef = nullptr;
89 90 91
QCefCookieManager *panel_cookies = nullptr;

void DestroyPanelCookieManager();
J
jp9000 已提交
92

J
jp9000 已提交
93 94
namespace {

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

101 102
extern volatile long insideEventLoop;

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

V
VodBox 已提交
109 110 111 112 113 114 115 116 117 118 119 120
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 已提交
121
template<typename T> static T GetOBSRef(QListWidgetItem *item)
P
Palana 已提交
122 123 124 125
{
	return item->data(static_cast<int>(QtDataRole::OBSRef)).value<T>();
}

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

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

143
	if (ret <= 0)
144 145
		return;

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

J
jp9000 已提交
150 151 152 153
	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");
154 155
	obs_add_module_path(config_bin, config_data);

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

165 166
extern obs_frontend_callbacks *InitializeAPIInterface(OBSBasic *main);

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

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

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

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

195 196
	setAttribute(Qt::WA_NativeWindow);

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

J
jp9000 已提交
207 208
	setAcceptDrops(true);

209 210
	api = InitializeAPIInterface(this);

211
	ui->setupUi(this);
212
	ui->previewDisabledWidget->setVisible(false);
J
jp9000 已提交
213

J
jp9000 已提交
214 215
	startingDockLayout = saveState();

216
	statsDock = new OBSDock();
217 218 219 220 221 222 223 224
	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 已提交
225
	copyActionsDynamicProperties();
226

227
	char styleSheetPath[512];
J
jp9000 已提交
228
	int ret = GetProfilePath(styleSheetPath, sizeof(styleSheetPath),
J
jp9000 已提交
229
				 "stylesheet.qss");
230
	if (ret > 0) {
H
HomeWorld 已提交
231
		if (QFile::exists(styleSheetPath)) {
J
jp9000 已提交
232 233
			QString path =
				QString("file:///") + QT_UTF8(styleSheetPath);
H
HomeWorld 已提交
234 235
			App()->setStyleSheet(path);
		}
236 237
	}

J
jp9000 已提交
238
	qRegisterMetaType<OBSScene>("OBSScene");
P
Palana 已提交
239
	qRegisterMetaType<OBSSceneItem>("OBSSceneItem");
J
jp9000 已提交
240
	qRegisterMetaType<OBSSource>("OBSSource");
P
Palana 已提交
241
	qRegisterMetaType<obs_hotkey_id>("obs_hotkey_id");
242
	qRegisterMetaType<SavedProjectorInfo *>("SavedProjectorInfo *");
P
Palana 已提交
243

J
jp9000 已提交
244 245
	qRegisterMetaTypeStreamOperators<std::vector<std::shared_ptr<OBSSignal>>>(
		"std::vector<std::shared_ptr<OBSSignal>>");
246
	qRegisterMetaTypeStreamOperators<OBSScene>("OBSScene");
247
	qRegisterMetaTypeStreamOperators<OBSSceneItem>("OBSSceneItem");
248

P
Palana 已提交
249 250 251
	ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false);
	ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false);

V
VodBox 已提交
252 253 254 255
	bool sceneGrid = config_get_bool(App()->GlobalConfig(), "BasicWindow",
					 "gridMode");
	ui->scenes->SetGridMode(sceneGrid);

256 257
	ui->scenes->setItemDelegate(new SceneRenameDelegate(ui->scenes));

258
	auto displayResize = [this]() {
259 260 261 262
		struct obs_video_info ovi;

		if (obs_get_video_info(&ovi))
			ResizePreview(ovi.base_width, ovi.base_height);
263 264 265 266
	};

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

P
pkv 已提交
268 269 270
	delete shortcutFilter;
	shortcutFilter = CreateShortcutFilter();
	installEventFilter(shortcutFilter);
P
Palana 已提交
271

272
	stringstream name;
J
jp9000 已提交
273
	name << "OBS " << App()->GetVersionString();
274 275 276
	blog(LOG_INFO, "%s", name.str().c_str());
	blog(LOG_INFO, "---------------------------------");

277
	UpdateTitleBar();
J
jp9000 已提交
278 279

	connect(ui->scenes->itemDelegate(),
J
jp9000 已提交
280 281 282 283 284
		SIGNAL(closeEditor(QWidget *,
				   QAbstractItemDelegate::EndEditHint)),
		this,
		SLOT(SceneNameEdited(QWidget *,
				     QAbstractItemDelegate::EndEditHint)));
J
jp9000 已提交
285

286
	cpuUsageInfo = os_cpu_usage_info_start();
J
jp9000 已提交
287
	cpuUsageTimer = new QTimer(this);
J
jp9000 已提交
288 289
	connect(cpuUsageTimer.data(), SIGNAL(timeout()), ui->statusbar,
		SLOT(UpdateCPUUsage()));
J
jp9000 已提交
290
	cpuUsageTimer->start(3000);
291

292 293 294 295
	diskFullTimer = new QTimer(this);
	connect(diskFullTimer, SIGNAL(timeout()), this,
		SLOT(CheckDiskSpaceRemaining()));

S
Shaolin 已提交
296 297 298 299 300 301 302 303
	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 已提交
304
		SLOT(EditSceneItemName()));
S
Shaolin 已提交
305 306
	ui->sourcesDock->addAction(renameSource);

307
#ifdef __APPLE__
S
Shaolin 已提交
308 309 310
	renameScene->setShortcut({Qt::Key_Return});
	renameSource->setShortcut({Qt::Key_Return});

311 312
	ui->actionRemoveSource->setShortcuts({Qt::Key_Backspace});
	ui->actionRemoveScene->setShortcuts({Qt::Key_Backspace});
313 314 315

	ui->action_Settings->setMenuRole(QAction::PreferencesRole);
	ui->actionE_xit->setMenuRole(QAction::QuitRole);
S
Shaolin 已提交
316 317 318
#else
	renameScene->setShortcut({Qt::Key_F2});
	renameSource->setShortcut({Qt::Key_F2});
319
#endif
320

J
jp9000 已提交
321
	auto addNudge = [this](const QKeySequence &seq, const char *s) {
322 323 324 325 326 327 328 329 330 331 332
		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 已提交
333 334 335 336 337 338

	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);
339
	assignDockToggle(statsDock, ui->toggleStats);
S
SuslikV 已提交
340 341 342 343 344 345 346

	//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 已提交
347
	ui->toggleStats->setChecked(false);
S
SuslikV 已提交
348

349 350
	QPoint curPos;

S
SuslikV 已提交
351 352
	//restore parent window geometry
	const char *geometry = config_get_string(App()->GlobalConfig(),
J
jp9000 已提交
353
						 "BasicWindow", "geometry");
S
SuslikV 已提交
354
	if (geometry != NULL) {
J
jp9000 已提交
355 356
		QByteArray byteArray =
			QByteArray::fromBase64(QByteArray(geometry));
S
SuslikV 已提交
357 358 359 360 361
		restoreGeometry(byteArray);

		QRect windowGeometry = normalGeometry();
		if (!WindowPositionValid(windowGeometry)) {
			QRect rect = App()->desktop()->geometry();
J
jp9000 已提交
362 363 364
			setGeometry(QStyle::alignedRect(Qt::LeftToRight,
							Qt::AlignCenter, size(),
							rect));
S
SuslikV 已提交
365
		}
366 367 368

		curPos = pos();
	} else {
J
jp9000 已提交
369 370
		QRect desktopRect =
			QGuiApplication::primaryScreen()->geometry();
371 372
		QSize adjSize = desktopRect.size() / 2 - size() / 2;
		curPos = QPoint(adjSize.width(), adjSize.height());
S
SuslikV 已提交
373
	}
374 375 376 377 378 379

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

	ui->previewLabel->setProperty("themeID", "previewProgramLabels");

J
jp9000 已提交
383 384
	bool labels = config_get_bool(GetGlobalConfig(), "BasicWindow",
				      "StudioModeLabels");
385 386 387 388 389

	if (!previewProgramMode)
		ui->previewLabel->setHidden(true);
	else
		ui->previewLabel->setHidden(!labels);
390 391 392 393 394 395 396

	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()));
397 398 399 400 401 402

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

405
static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent,
J
jp9000 已提交
406
			    vector<OBSSource> &audioSources)
407
{
408
	obs_source_t *source = obs_get_output_source(channel);
409 410 411
	if (!source)
		return;

412 413
	audioSources.push_back(source);

414
	obs_data_t *data = obs_save_source(source);
415

J
jp9000 已提交
416
	obs_data_set_obj(parent, name, data);
417 418 419 420 421

	obs_data_release(data);
	obs_source_release(source);
}

422
static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder,
J
jp9000 已提交
423 424 425 426 427
				    obs_data_array_t *quickTransitionData,
				    int transitionDuration,
				    obs_data_array_t *transitions,
				    OBSScene &scene, OBSSource &curProgramScene,
				    obs_data_array_t *savedProjectorList)
428
{
429 430 431 432 433 434 435
	obs_data_t *saveData = obs_data_create();

	vector<OBSSource> audioSources;
	audioSources.reserve(5);

	SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
	SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
J
jp9000 已提交
436 437 438 439
	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);
440

441 442 443
	/* -------------------------------- */
	/* save non-group sources           */

J
jp9000 已提交
444
	auto FilterAudioSources = [&](obs_source_t *source) {
445 446 447
		if (obs_source_is_group(source))
			return false;

448
		return find(begin(audioSources), end(audioSources), source) ==
J
jp9000 已提交
449
		       end(audioSources);
450 451 452 453
	};
	using FilterAudioSources_t = decltype(FilterAudioSources);

	obs_data_array_t *sourcesArray = obs_save_sources_filtered(
J
jp9000 已提交
454 455 456 457 458
		[](void *data, obs_source_t *source) {
			return (*static_cast<FilterAudioSources_t *>(data))(
				source);
		},
		static_cast<void *>(&FilterAudioSources));
459

460 461 462 463 464
	/* -------------------------------- */
	/* 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 已提交
465 466 467 468
		[](void *, obs_source_t *source) {
			return obs_source_is_group(source);
		},
		nullptr);
469 470 471

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

472 473
	obs_source_t *transition = obs_get_output_source(0);
	obs_source_t *currentScene = obs_scene_get_source(scene);
J
jp9000 已提交
474 475
	const char *sceneName = obs_source_get_name(currentScene);
	const char *programName = obs_source_get_name(curProgramScene);
476

J
jp9000 已提交
477 478
	const char *sceneCollection = config_get_string(
		App()->GlobalConfig(), "Basic", "SceneCollection");
J
jp9000 已提交
479

J
jp9000 已提交
480
	obs_data_set_string(saveData, "current_scene", sceneName);
481
	obs_data_set_string(saveData, "current_program_scene", programName);
J
jp9000 已提交
482
	obs_data_set_array(saveData, "scene_order", sceneOrder);
J
jp9000 已提交
483
	obs_data_set_string(saveData, "name", sceneCollection);
J
jp9000 已提交
484
	obs_data_set_array(saveData, "sources", sourcesArray);
485
	obs_data_set_array(saveData, "groups", groupsArray);
486
	obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
J
jp9000 已提交
487
	obs_data_set_array(saveData, "transitions", transitions);
C
cg2121 已提交
488
	obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
489
	obs_data_array_release(sourcesArray);
490
	obs_data_array_release(groupsArray);
491 492

	obs_data_set_string(saveData, "current_transition",
J
jp9000 已提交
493
			    obs_source_get_name(transition));
494 495
	obs_data_set_int(saveData, "transition_duration", transitionDuration);
	obs_source_release(transition);
496 497 498 499

	return saveData;
}

S
Socapex 已提交
500 501 502 503
void OBSBasic::copyActionsDynamicProperties()
{
	// Themes need the QAction dynamic properties
	for (QAction *x : ui->scenesToolbar->actions()) {
J
jp9000 已提交
504
		QWidget *temp = ui->scenesToolbar->widgetForAction(x);
S
Socapex 已提交
505 506 507 508 509 510 511

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

	for (QAction *x : ui->sourcesToolbar->actions()) {
J
jp9000 已提交
512
		QWidget *temp = ui->sourcesToolbar->widgetForAction(x);
S
Socapex 已提交
513 514 515 516 517 518 519

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

S
Shaolin 已提交
520 521
void OBSBasic::UpdateVolumeControlsDecayRate()
{
J
jp9000 已提交
522 523
	double meterDecayRate =
		config_get_double(basicConfig, "Audio", "MeterDecayRate");
S
Shaolin 已提交
524 525 526 527 528 529

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

530 531
void OBSBasic::UpdateVolumeControlsPeakMeterType()
{
J
jp9000 已提交
532 533
	uint32_t peakMeterTypeIdx =
		config_get_uint(basicConfig, "Audio", "PeakMeterType");
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552

	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);
	}
}

553 554
void OBSBasic::ClearVolumeControls()
{
C
craftwar 已提交
555 556
	for (VolControl *vol : volumes)
		delete vol;
557 558 559 560

	volumes.clear();
}

J
jp9000 已提交
561 562 563 564 565 566 567
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 已提交
568
				    QT_TO_UTF8(ui->scenes->item(i)->text()));
J
jp9000 已提交
569 570 571 572 573 574 575
		obs_data_array_push_back(sceneOrder, data);
		obs_data_release(data);
	}

	return sceneOrder;
}

C
cg2121 已提交
576 577
obs_data_array_t *OBSBasic::SaveProjectors()
{
578
	obs_data_array_t *savedProjectors = obs_data_array_create();
C
cg2121 已提交
579

580 581 582
	auto saveProjector = [savedProjectors](OBSProjector *projector) {
		if (!projector)
			return;
R
Ryan Foster 已提交
583 584

		obs_data_t *data = obs_data_create();
585
		ProjectorType type = projector->GetProjectorType();
S
Shaolin 已提交
586 587 588 589 590 591 592 593 594 595 596
		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;
		}
597 598
		obs_data_set_int(data, "monitor", projector->GetMonitor());
		obs_data_set_int(data, "type", static_cast<int>(type));
J
jp9000 已提交
599 600 601
		obs_data_set_string(
			data, "geometry",
			projector->saveGeometry().toBase64().constData());
602
		obs_data_array_push_back(savedProjectors, data);
R
Ryan Foster 已提交
603
		obs_data_release(data);
604
	};
R
Ryan Foster 已提交
605

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

609
	return savedProjectors;
S
Shaolin 已提交
610 611
}

612 613
void OBSBasic::Save(const char *file)
{
614 615 616 617 618
	OBSScene scene = GetCurrentScene();
	OBSSource curProgramScene = OBSGetStrongRef(programScene);
	if (!curProgramScene)
		curProgramScene = obs_scene_get_source(scene);

J
jp9000 已提交
619
	obs_data_array_t *sceneOrder = SaveSceneListOrder();
J
jp9000 已提交
620
	obs_data_array_t *transitions = SaveTransitions();
621
	obs_data_array_t *quickTrData = SaveQuickTransitions();
C
cg2121 已提交
622
	obs_data_array_t *savedProjectorList = SaveProjectors();
J
jp9000 已提交
623 624 625
	obs_data_t *saveData = GenerateSaveData(
		sceneOrder, quickTrData, ui->transitionDuration->value(),
		transitions, scene, curProgramScene, savedProjectorList);
626

J
jp9000 已提交
627
	obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
628
	obs_data_set_bool(saveData, "scaling_enabled",
J
jp9000 已提交
629
			  ui->preview->IsFixedScaling());
630
	obs_data_set_int(saveData, "scaling_level",
J
jp9000 已提交
631
			 ui->preview->GetScalingLevel());
632
	obs_data_set_double(saveData, "scaling_off_x",
J
jp9000 已提交
633
			    ui->preview->GetScrollX());
634
	obs_data_set_double(saveData, "scaling_off_y",
J
jp9000 已提交
635
			    ui->preview->GetScrollY());
J
jp9000 已提交
636

J
jp9000 已提交
637 638 639 640 641 642 643
	if (api) {
		obs_data_t *moduleObj = obs_data_create();
		api->on_save(moduleObj);
		obs_data_set_obj(saveData, "modules", moduleObj);
		obs_data_release(moduleObj);
	}

644 645
	if (!obs_data_save_json_safe(saveData, file, "tmp", "bak"))
		blog(LOG_ERROR, "Could not save scene data to %s", file);
646 647

	obs_data_release(saveData);
J
jp9000 已提交
648
	obs_data_array_release(sceneOrder);
649
	obs_data_array_release(quickTrData);
J
jp9000 已提交
650
	obs_data_array_release(transitions);
C
cg2121 已提交
651
	obs_data_array_release(savedProjectorList);
652 653
}

I
Ilya M 已提交
654 655 656 657 658 659 660 661 662 663 664 665 666
void OBSBasic::DeferSaveBegin()
{
	os_atomic_inc_long(&disableSaving);
}

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

667
static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
668
{
669
	obs_data_t *data = obs_data_get_obj(parent, name);
670 671 672
	if (!data)
		return;

673
	obs_source_t *source = obs_load_source(data);
674 675 676 677 678 679 680 681
	if (source) {
		obs_set_output_source(channel, source);
		obs_source_release(source);
	}

	obs_data_release(data);
}

682 683 684
static inline bool HasAudioDevices(const char *source_id)
{
	const char *output_id = source_id;
685
	obs_properties_t *props = obs_get_source_properties(output_id);
686 687 688 689 690 691 692 693 694 695 696 697 698 699
	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;
}

700
void OBSBasic::CreateFirstRunSources()
701
{
702
	bool hasDesktopAudio = HasAudioDevices(App()->OutputAudioSource());
J
jp9000 已提交
703
	bool hasInputAudio = HasAudioDevices(App()->InputAudioSource());
704 705 706

	if (hasDesktopAudio)
		ResetAudioDevice(App()->OutputAudioSource(), "default",
J
jp9000 已提交
707
				 Str("Basic.DesktopDevice1"), 1);
708 709
	if (hasInputAudio)
		ResetAudioDevice(App()->InputAudioSource(), "default",
J
jp9000 已提交
710
				 Str("Basic.AuxDevice1"), 3);
711 712
}

713
void OBSBasic::CreateDefaultScene(bool firstStart)
714 715 716 717
{
	disableSaving++;

	ClearSceneData();
718 719 720 721
	InitDefaultTransitions();
	CreateDefaultQuickTransitions();
	ui->transitionDuration->setValue(300);
	SetTransition(fadeTransition);
722

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

725
	if (firstStart)
726
		CreateFirstRunSources();
727

728
	SetCurrentScene(scene, true);
729
	obs_scene_release(scene);
J
jp9000 已提交
730 731

	disableSaving--;
732 733
}

J
jp9000 已提交
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
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 已提交
763 764
void OBSBasic::LoadSavedProjectors(obs_data_array_t *array)
{
765 766 767 768 769
	for (SavedProjectorInfo *info : savedProjectorsArray) {
		delete info;
	}
	savedProjectorsArray.clear();

C
cg2121 已提交
770 771 772 773 774
	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);

775 776
		SavedProjectorInfo *info = new SavedProjectorInfo();
		info->monitor = obs_data_get_int(data, "monitor");
J
jp9000 已提交
777 778 779 780
		info->type = static_cast<ProjectorType>(
			obs_data_get_int(data, "type"));
		info->geometry =
			std::string(obs_data_get_string(data, "geometry"));
S
Shaolin 已提交
781
		info->name = std::string(obs_data_get_string(data, "name"));
782
		savedProjectorsArray.emplace_back(info);
S
Shaolin 已提交
783 784 785 786 787

		obs_data_release(data);
	}
}

J
jp9000 已提交
788
static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val)
789 790 791 792 793 794 795 796 797 798 799 800
{
	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 已提交
801
static bool LogSceneItem(obs_scene_t *, obs_sceneitem_t *item, void *v_val)
802 803 804 805
{
	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 已提交
806 807 808 809 810
	int indent_count = (int)(intptr_t)v_val;
	string indent;

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

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

814 815 816 817 818 819
	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 已提交
820 821
				? "monitor only"
				: "monitor and output";
822

M
Matt Gajownik 已提交
823
		blog(LOG_INFO, "    %s- monitoring: %s", indent.c_str(), type);
824
	}
M
Matt Gajownik 已提交
825
	int child_indent = 1 + indent_count;
J
jp9000 已提交
826 827
	obs_source_enum_filters(source, LogFilter,
				(void *)(intptr_t)child_indent);
M
Matt Gajownik 已提交
828
	if (obs_sceneitem_is_group(item))
J
jp9000 已提交
829 830
		obs_sceneitem_group_enum_items(item, LogSceneItem,
					       (void *)(intptr_t)child_indent);
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
	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 已提交
847 848
		obs_scene_enum_items(scene, LogSceneItem, (void *)(intptr_t)1);
		obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
849 850 851 852 853
	}

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

854 855
void OBSBasic::Load(const char *file)
{
856 857 858 859 860
	disableSaving++;

	obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
	if (!data) {
		disableSaving--;
861
		blog(LOG_INFO, "No scene file found, creating default scene");
862
		CreateDefaultScene(true);
J
jp9000 已提交
863
		SaveProject();
864
		return;
865
	}
866

867
	ClearSceneData();
868
	InitDefaultTransitions();
869

870 871 872 873
	obs_data_t *modulesObj = obs_data_get_obj(data, "modules");
	if (api)
		api->on_preload(modulesObj);

J
jp9000 已提交
874
	obs_data_array_t *sceneOrder = obs_data_get_array(data, "scene_order");
J
jp9000 已提交
875 876 877 878 879 880 881 882
	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");
883

884 885 886 887 888 889
	if (!opt_starting_scene.empty()) {
		programSceneName = opt_starting_scene.c_str();
		if (!IsPreviewProgramMode())
			sceneName = opt_starting_scene.c_str();
	}

890 891 892 893 894 895
	int newDuration = obs_data_get_int(data, "transition_duration");
	if (!newDuration)
		newDuration = 300;

	if (!transitionName)
		transitionName = obs_source_get_name(fadeTransition);
J
jp9000 已提交
896 897

	const char *curSceneCollection = config_get_string(
J
jp9000 已提交
898
		App()->GlobalConfig(), "Basic", "SceneCollection");
J
jp9000 已提交
899 900 901

	obs_data_set_default_string(data, "name", curSceneCollection);

J
jp9000 已提交
902 903 904 905
	const char *name = obs_data_get_string(data, "name");
	obs_source_t *curScene;
	obs_source_t *curProgramScene;
	obs_source_t *curTransition;
906

J
jp9000 已提交
907 908 909
	if (!name || !*name)
		name = curSceneCollection;

910 911
	LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
	LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
J
jp9000 已提交
912 913 914 915
	LoadAudioDevice(AUX_AUDIO_1, 3, data);
	LoadAudioDevice(AUX_AUDIO_2, 4, data);
	LoadAudioDevice(AUX_AUDIO_3, 5, data);
	LoadAudioDevice(AUX_AUDIO_4, 6, data);
916

917 918 919 920 921 922 923
	if (!sources) {
		sources = groups;
		groups = nullptr;
	} else {
		obs_data_array_push_back_array(sources, groups);
	}

924
	obs_load_sources(sources, nullptr, nullptr);
925

J
jp9000 已提交
926 927
	if (transitions)
		LoadTransitions(transitions);
J
jp9000 已提交
928 929 930
	if (sceneOrder)
		LoadSceneListOrder(sceneOrder);

J
jp9000 已提交
931 932
	obs_data_array_release(transitions);

933 934 935 936 937 938 939
	curTransition = FindTransition(transitionName);
	if (!curTransition)
		curTransition = fadeTransition;

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

940
retryScene:
941
	curScene = obs_get_source_by_name(sceneName);
942
	curProgramScene = obs_get_source_by_name(programSceneName);
943 944 945 946 947

	/* 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 已提交
948 949
		programSceneName =
			obs_data_get_string(data, "current_program_scene");
950 951 952 953 954 955
		obs_source_release(curScene);
		obs_source_release(curProgramScene);
		opt_starting_scene.clear();
		goto retryScene;
	}

956 957 958 959 960 961 962 963
	if (!curProgramScene) {
		curProgramScene = curScene;
		obs_source_addref(curScene);
	}

	SetCurrentScene(curScene, true);
	if (IsPreviewProgramMode())
		TransitionToScene(curProgramScene, true);
964
	obs_source_release(curScene);
965
	obs_source_release(curProgramScene);
966 967

	obs_data_array_release(sources);
968
	obs_data_array_release(groups);
J
jp9000 已提交
969
	obs_data_array_release(sceneOrder);
J
jp9000 已提交
970

971 972 973
	/* ------------------- */

	bool projectorSave = config_get_bool(GetGlobalConfig(), "BasicWindow",
J
jp9000 已提交
974
					     "SaveProjectors");
975 976

	if (projectorSave) {
J
jp9000 已提交
977 978
		obs_data_array_t *savedProjectors =
			obs_data_get_array(data, "saved_projectors");
979

980
		if (savedProjectors) {
981
			LoadSavedProjectors(savedProjectors);
982 983 984
			OpenSavedProjectors();
			activateWindow();
		}
985 986 987 988 989 990

		obs_data_array_release(savedProjectors);
	}

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

J
jp9000 已提交
991 992 993 994
	std::string file_base = strrchr(file, '/') + 1;
	file_base.erase(file_base.size() - 5, 5);

	config_set_string(App()->GlobalConfig(), "Basic", "SceneCollection",
J
jp9000 已提交
995
			  name);
J
jp9000 已提交
996
	config_set_string(App()->GlobalConfig(), "Basic", "SceneCollectionFile",
J
jp9000 已提交
997
			  file_base.c_str());
J
jp9000 已提交
998

J
jp9000 已提交
999 1000
	obs_data_array_t *quickTransitionData =
		obs_data_get_array(data, "quick_transitions");
1001 1002 1003 1004 1005
	LoadQuickTransitions(quickTransitionData);
	obs_data_array_release(quickTransitionData);

	RefreshQuickTransitions();

J
jp9000 已提交
1006 1007 1008 1009
	bool previewLocked = obs_data_get_bool(data, "preview_locked");
	ui->preview->SetLocked(previewLocked);
	ui->actionLockPreview->setChecked(previewLocked);

1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
	/* ---------------------- */

	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 已提交
1020
	}
1021
	ui->preview->SetFixedScaling(fixedScaling);
J
Joseph El-Khouri 已提交
1022

1023
	/* ---------------------- */
J
Joseph El-Khouri 已提交
1024

1025
	if (api)
J
jp9000 已提交
1026 1027
		api->on_load(modulesObj);

1028
	obs_data_release(modulesObj);
1029
	obs_data_release(data);
J
jp9000 已提交
1030

1031 1032 1033
	if (!opt_starting_scene.empty())
		opt_starting_scene.clear();

1034
	if (opt_start_streaming) {
1035
		blog(LOG_INFO, "Starting stream due to command line parameter");
1036
		QMetaObject::invokeMethod(this, "StartStreaming",
J
jp9000 已提交
1037
					  Qt::QueuedConnection);
1038 1039 1040 1041
		opt_start_streaming = false;
	}

	if (opt_start_recording) {
J
jp9000 已提交
1042 1043
		blog(LOG_INFO,
		     "Starting recording due to command line parameter");
1044
		QMetaObject::invokeMethod(this, "StartRecording",
J
jp9000 已提交
1045
					  Qt::QueuedConnection);
1046 1047 1048
		opt_start_recording = false;
	}

C
cg2121 已提交
1049 1050
	if (opt_start_replaybuffer) {
		QMetaObject::invokeMethod(this, "StartReplayBuffer",
J
jp9000 已提交
1051
					  Qt::QueuedConnection);
C
cg2121 已提交
1052 1053 1054
		opt_start_replaybuffer = false;
	}

1055
	copyStrings.clear();
1056 1057
	copyFiltersString = nullptr;

1058 1059
	LogScenes();

J
jp9000 已提交
1060
	disableSaving--;
1061

1062
	if (api) {
1063
		api->on_event(OBS_FRONTEND_EVENT_SCENE_CHANGED);
1064 1065
		api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
	}
1066 1067
}

J
jp9000 已提交
1068
#define SERVICE_PATH "service.json"
1069 1070 1071 1072 1073 1074

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

1075
	char serviceJsonPath[512];
J
jp9000 已提交
1076
	int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
J
jp9000 已提交
1077
				 SERVICE_PATH);
1078
	if (ret <= 0)
1079 1080
		return;

J
jp9000 已提交
1081
	obs_data_t *data = obs_data_create();
1082
	obs_data_t *settings = obs_service_get_settings(service);
1083

1084
	obs_data_set_string(data, "type", obs_service_get_type(service));
J
jp9000 已提交
1085
	obs_data_set_obj(data, "settings", settings);
1086

1087 1088
	if (!obs_data_save_json_safe(data, serviceJsonPath, "tmp", "bak"))
		blog(LOG_WARNING, "Failed to save service");
1089 1090 1091 1092 1093 1094 1095 1096 1097

	obs_data_release(settings);
	obs_data_release(data);
}

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

1098
	char serviceJsonPath[512];
J
jp9000 已提交
1099
	int ret = GetProfilePath(serviceJsonPath, sizeof(serviceJsonPath),
J
jp9000 已提交
1100
				 SERVICE_PATH);
1101
	if (ret <= 0)
1102 1103
		return false;

J
jp9000 已提交
1104 1105
	obs_data_t *data =
		obs_data_create_from_json_file_safe(serviceJsonPath, "bak");
1106 1107

	obs_data_set_default_string(data, "type", "rtmp_common");
J
jp9000 已提交
1108
	type = obs_data_get_string(data, "type");
1109

1110
	obs_data_t *settings = obs_data_get_obj(data, "settings");
P
Palana 已提交
1111
	obs_data_t *hotkey_data = obs_data_get_obj(data, "hotkeys");
1112

1113
	service = obs_service_create(type, "default_service", settings,
J
jp9000 已提交
1114
				     hotkey_data);
1115
	obs_service_release(service);
1116

P
Palana 已提交
1117
	obs_data_release(hotkey_data);
1118 1119 1120 1121 1122 1123 1124 1125
	obs_data_release(settings);
	obs_data_release(data);

	return !!service;
}

bool OBSBasic::InitService()
{
P
Palana 已提交
1126 1127
	ProfileScope("OBSBasic::InitService");

1128 1129 1130
	if (LoadService())
		return true;

1131
	service = obs_service_create("rtmp_common", "default_service", nullptr,
J
jp9000 已提交
1132
				     nullptr);
1133 1134
	if (!service)
		return false;
1135
	obs_service_release(service);
1136 1137 1138 1139

	return true;
}

J
jp9000 已提交
1140 1141 1142
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};
1143

1144 1145
extern void CheckExistingCookieId();

1146 1147
bool OBSBasic::InitBasicConfigDefaults()
{
J
jp9000 已提交
1148
	QList<QScreen *> screens = QGuiApplication::screens();
1149

1150
	if (!screens.size()) {
1151
		OBSErrorBox(NULL, "There appears to be no monitors.  Er, this "
J
jp9000 已提交
1152
				  "technically shouldn't be possible.");
1153 1154 1155
		return false;
	}

1156 1157 1158 1159
	QScreen *primaryScreen = QGuiApplication::primaryScreen();

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

J
jp9000 已提交
1161 1162
	bool oldResolutionDefaults = config_get_bool(
		App()->GlobalConfig(), "General", "Pre19Defaults");
1163 1164 1165 1166 1167 1168 1169 1170 1171

	/* 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 已提交
1172 1173 1174 1175 1176 1177 1178 1179
	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 已提交
1180
						"FFAudioTrack");
P
pkviet 已提交
1181
		config_set_int(basicConfig, "AdvOut", "FFAudioMixes",
J
jp9000 已提交
1182
			       1LL << (track - 1));
P
pkviet 已提交
1183 1184 1185 1186
		config_set_bool(basicConfig, "AdvOut", "Pre22.1Settings", true);
		changed = true;
	}

1187 1188 1189 1190 1191
	/* ----------------------------------------------------- */
	/* 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 已提交
1192 1193
		uint64_t track =
			config_get_uint(basicConfig, "AdvOut", "RecTrackIndex");
1194 1195 1196
		track = 1ULL << (track - 1);
		config_set_uint(basicConfig, "AdvOut", "RecTracks", track);
		config_remove_value(basicConfig, "AdvOut", "RecTrackIndex");
P
pkviet 已提交
1197
		changed = true;
1198 1199
	}

1200 1201 1202 1203 1204 1205 1206 1207 1208
	/* ----------------------------------------------------- */
	/* 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;
	}

1209 1210
	/* ----------------------------------------------------- */

P
pkviet 已提交
1211 1212 1213 1214 1215
	if (changed)
		config_save_safe(basicConfig, "tmp", nullptr);

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

1216
	config_set_default_string(basicConfig, "Output", "Mode", "Simple");
J
jp9000 已提交
1217

1218
	config_set_default_string(basicConfig, "SimpleOutput", "FilePath",
J
jp9000 已提交
1219
				  GetDefaultVideoSavePath().c_str());
1220
	config_set_default_string(basicConfig, "SimpleOutput", "RecFormat",
1221
				  "mkv");
J
jp9000 已提交
1222 1223 1224 1225 1226 1227
	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 已提交
1228
	config_set_default_string(basicConfig, "SimpleOutput", "Preset",
J
jp9000 已提交
1229
				  "veryfast");
1230
	config_set_default_string(basicConfig, "SimpleOutput", "NVENCPreset",
J
jp9000 已提交
1231
				  "hq");
1232
	config_set_default_string(basicConfig, "SimpleOutput", "RecQuality",
J
jp9000 已提交
1233
				  "Stream");
1234 1235 1236
	config_set_default_bool(basicConfig, "SimpleOutput", "RecRB", false);
	config_set_default_int(basicConfig, "SimpleOutput", "RecRBTime", 20);
	config_set_default_int(basicConfig, "SimpleOutput", "RecRBSize", 512);
1237
	config_set_default_string(basicConfig, "SimpleOutput", "RecRBPrefix",
J
jp9000 已提交
1238
				  "Replay");
1239

J
jp9000 已提交
1240 1241 1242 1243
	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 已提交
1244 1245 1246 1247 1248
	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 已提交
1249
				  GetDefaultVideoSavePath().c_str());
1250
	config_set_default_string(basicConfig, "AdvOut", "RecFormat", "mkv");
J
jp9000 已提交
1251 1252 1253
	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");
1254
	config_set_default_uint(basicConfig, "AdvOut", "FLVTrack", 1);
J
jp9000 已提交
1255 1256

	config_set_default_bool(basicConfig, "AdvOut", "FFOutputToFile", true);
1257
	config_set_default_string(basicConfig, "AdvOut", "FFFilePath",
J
jp9000 已提交
1258
				  GetDefaultVideoSavePath().c_str());
1259
	config_set_default_string(basicConfig, "AdvOut", "FFExtension", "mp4");
J
jp9000 已提交
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
	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);
1280

1281 1282 1283 1284 1285 1286 1287 1288
	/* 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);
	}

1289
	config_set_default_string(basicConfig, "Output", "FilenameFormatting",
J
jp9000 已提交
1290
				  "%CCYY-%MM-%DD %hh-%mm-%ss");
1291

J
jp9000 已提交
1292 1293 1294
	config_set_default_bool(basicConfig, "Output", "DelayEnable", false);
	config_set_default_uint(basicConfig, "Output", "DelaySec", 20);
	config_set_default_bool(basicConfig, "Output", "DelayPreserve", true);
1295

J
jp9000 已提交
1296 1297 1298
	config_set_default_bool(basicConfig, "Output", "Reconnect", true);
	config_set_default_uint(basicConfig, "Output", "RetryDelay", 10);
	config_set_default_uint(basicConfig, "Output", "MaxRetries", 20);
1299

1300
	config_set_default_string(basicConfig, "Output", "BindIP", "default");
J
jp9000 已提交
1301 1302 1303 1304
	config_set_default_bool(basicConfig, "Output", "NewSocketLoopEnable",
				false);
	config_set_default_bool(basicConfig, "Output", "LowLatencyEnable",
				false);
1305

1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
	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 已提交
1318 1319
	config_set_default_uint(basicConfig, "Video", "OutputCX", scale_cx);
	config_set_default_uint(basicConfig, "Video", "OutputCY", scale_cy);
1320

1321 1322 1323 1324 1325 1326 1327 1328 1329
	/* 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 已提交
1330
	config_set_default_uint(basicConfig, "Video", "FPSType", 0);
1331
	config_set_default_string(basicConfig, "Video", "FPSCommon", "30");
J
jp9000 已提交
1332 1333 1334
	config_set_default_uint(basicConfig, "Video", "FPSInt", 30);
	config_set_default_uint(basicConfig, "Video", "FPSNum", 30);
	config_set_default_uint(basicConfig, "Video", "FPSDen", 1);
1335
	config_set_default_string(basicConfig, "Video", "ScaleType", "bicubic");
1336
	config_set_default_string(basicConfig, "Video", "ColorFormat", "NV12");
1337
	config_set_default_string(basicConfig, "Video", "ColorSpace", "601");
1338
	config_set_default_string(basicConfig, "Video", "ColorRange",
J
jp9000 已提交
1339
				  "Partial");
1340

1341
	config_set_default_string(basicConfig, "Audio", "MonitoringDeviceId",
J
jp9000 已提交
1342 1343 1344 1345 1346 1347
				  "default");
	config_set_default_string(
		basicConfig, "Audio", "MonitoringDeviceName",
		Str("Basic.Settings.Advanced.Audio.MonitoringDevice"
		    ".Default"));
	config_set_default_uint(basicConfig, "Audio", "SampleRate", 44100);
1348
	config_set_default_string(basicConfig, "Audio", "ChannelSetup",
J
jp9000 已提交
1349
				  "Stereo");
S
Shaolin 已提交
1350
	config_set_default_double(basicConfig, "Audio", "MeterDecayRate",
J
jp9000 已提交
1351 1352
				  VOLUME_METER_DECAY_FAST);
	config_set_default_uint(basicConfig, "Audio", "PeakMeterType", 0);
1353

1354 1355
	CheckExistingCookieId();

1356 1357 1358
	return true;
}

1359 1360 1361 1362
extern bool EncoderAvailable(const char *encoder);

void OBSBasic::InitBasicConfigDefaults2()
{
J
jp9000 已提交
1363 1364
	bool oldEncDefaults = config_get_bool(App()->GlobalConfig(), "General",
					      "Pre23Defaults");
1365 1366 1367
	bool useNV = EncoderAvailable("ffmpeg_nvenc") && !oldEncDefaults;

	config_set_default_string(basicConfig, "SimpleOutput", "StreamEncoder",
J
jp9000 已提交
1368 1369
				  useNV ? SIMPLE_ENCODER_NVENC
					: SIMPLE_ENCODER_X264);
1370
	config_set_default_string(basicConfig, "SimpleOutput", "RecEncoder",
J
jp9000 已提交
1371 1372
				  useNV ? SIMPLE_ENCODER_NVENC
					: SIMPLE_ENCODER_X264);
1373 1374
}

1375 1376
bool OBSBasic::InitBasicConfig()
{
P
Palana 已提交
1377 1378
	ProfileScope("OBSBasic::InitBasicConfig");

1379
	char configPath[512];
J
jp9000 已提交
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392

	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");
1393 1394 1395 1396
	if (ret <= 0) {
		OBSErrorBox(nullptr, "Failed to get base.ini path");
		return false;
	}
1397

1398 1399 1400
	int code = basicConfig.Open(configPath, CONFIG_OPEN_ALWAYS);
	if (code != CONFIG_SUCCESS) {
		OBSErrorBox(NULL, "Failed to open basic.ini: %d", code);
1401 1402 1403
		return false;
	}

J
jp9000 已提交
1404 1405
	if (config_get_string(basicConfig, "General", "Name") == nullptr) {
		const char *curName = config_get_string(App()->GlobalConfig(),
J
jp9000 已提交
1406
							"Basic", "Profile");
J
jp9000 已提交
1407 1408

		config_set_string(basicConfig, "General", "Name", curName);
1409
		basicConfig.SaveSafe("tmp");
J
jp9000 已提交
1410 1411
	}

1412 1413 1414
	return InitBasicConfigDefaults();
}

1415 1416
void OBSBasic::InitOBSCallbacks()
{
P
Palana 已提交
1417 1418
	ProfileScope("OBSBasic::InitOBSCallbacks");

P
Palana 已提交
1419
	signalHandlers.reserve(signalHandlers.size() + 6);
1420
	signalHandlers.emplace_back(obs_get_signal_handler(), "source_create",
J
jp9000 已提交
1421
				    OBSBasic::SourceCreated, this);
P
Palana 已提交
1422
	signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove",
J
jp9000 已提交
1423
				    OBSBasic::SourceRemoved, this);
P
Palana 已提交
1424
	signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate",
J
jp9000 已提交
1425 1426 1427 1428
				    OBSBasic::SourceActivated, this);
	signalHandlers.emplace_back(obs_get_signal_handler(),
				    "source_deactivate",
				    OBSBasic::SourceDeactivated, this);
1429 1430 1431 1432 1433 1434
	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 已提交
1435
	signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename",
J
jp9000 已提交
1436
				    OBSBasic::SourceRenamed, this);
1437 1438
}

J
jp9000 已提交
1439 1440
void OBSBasic::InitPrimitives()
{
P
Palana 已提交
1441 1442
	ProfileScope("OBSBasic::InitPrimitives");

J
jp9000 已提交
1443
	obs_enter_graphics();
J
jp9000 已提交
1444

1445
	gs_render_start(true);
J
jp9000 已提交
1446 1447 1448 1449 1450
	gs_vertex2f(0.0f, 0.0f);
	gs_vertex2f(0.0f, 1.0f);
	gs_vertex2f(1.0f, 1.0f);
	gs_vertex2f(1.0f, 0.0f);
	gs_vertex2f(0.0f, 0.0f);
1451
	box = gs_render_save();
J
jp9000 已提交
1452

1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
	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();

1473
	gs_render_start(true);
J
jp9000 已提交
1474
	for (int i = 0; i <= 360; i += (360 / 20)) {
J
jp9000 已提交
1475 1476 1477
		float pos = RAD(float(i));
		gs_vertex2f(cosf(pos), sinf(pos));
	}
1478
	circle = gs_render_save();
J
jp9000 已提交
1479

J
jp9000 已提交
1480
	obs_leave_graphics();
J
jp9000 已提交
1481 1482
}

J
jp9000 已提交
1483 1484 1485 1486 1487 1488 1489 1490
void OBSBasic::ReplayBufferClicked()
{
	if (outputHandler->ReplayBufferActive())
		StopReplayBuffer();
	else
		StartReplayBuffer();
};

J
jp9000 已提交
1491 1492
void OBSBasic::ResetOutputs()
{
P
Palana 已提交
1493 1494
	ProfileScope("OBSBasic::ResetOutputs");

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

J
jp9000 已提交
1498 1499
	if (!outputHandler || !outputHandler->Active()) {
		outputHandler.reset();
J
jp9000 已提交
1500 1501
		outputHandler.reset(advOut ? CreateAdvancedOutputHandler(this)
					   : CreateSimpleOutputHandler(this));
1502

J
jp9000 已提交
1503
		delete replayBufferButton;
1504
		delete replayLayout;
J
jp9000 已提交
1505 1506

		if (outputHandler->replayBuffer) {
1507
			replayBufferButton = new ReplayBufferButton(
J
jp9000 已提交
1508
				QTStr("Basic.Main.StartReplayBuffer"), this);
1509
			replayBufferButton->setCheckable(true);
1510
			connect(replayBufferButton.data(),
1511
				&QPushButton::clicked, this,
J
jp9000 已提交
1512
				&OBSBasic::ReplayBufferClicked);
J
jp9000 已提交
1513

1514 1515 1516
			replayLayout = new QHBoxLayout(this);
			replayLayout->addWidget(replayBufferButton);

J
jp9000 已提交
1517 1518
			replayBufferButton->setProperty("themeID",
							"replayBufferButton");
1519
			ui->buttonsVLayout->insertLayout(2, replayLayout);
J
jp9000 已提交
1520
		}
1521

J
jp9000 已提交
1522 1523
		if (sysTrayReplayBuffer)
			sysTrayReplayBuffer->setEnabled(
J
jp9000 已提交
1524
				!!outputHandler->replayBuffer);
J
jp9000 已提交
1525 1526 1527 1528 1529
	} else {
		outputHandler->Update();
	}
}

J
jp9000 已提交
1530
static void AddProjectorMenuMonitors(QMenu *parent, QObject *target,
J
jp9000 已提交
1531
				     const char *slot);
J
jp9000 已提交
1532

1533 1534 1535 1536
#define STARTUP_SEPARATOR \
	"==== Startup complete ==============================================="
#define SHUTDOWN_SEPARATOR \
	"==== Shutting down =================================================="
1537

J
jp9000 已提交
1538
#define UNSUPPORTED_ERROR                                                     \
1539 1540 1541
	"Failed to initialize video:\n\nRequired graphics API functionality " \
	"not found.  Your GPU may not be supported."

J
jp9000 已提交
1542
#define UNKNOWN_ERROR                                                  \
1543 1544
	"Failed to initialize video.  Your GPU may not be supported, " \
	"or your graphics drivers may need to be updated."
1545

1546 1547
void OBSBasic::OBSInit()
{
P
Palana 已提交
1548 1549
	ProfileScope("OBSBasic::OBSInit");

J
jp9000 已提交
1550 1551
	const char *sceneCollection = config_get_string(
		App()->GlobalConfig(), "Basic", "SceneCollectionFile");
1552
	char savePath[512];
J
jp9000 已提交
1553 1554 1555 1556 1557 1558 1559
	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 已提交
1560
		       sceneCollection);
1561
	if (ret <= 0)
J
jp9000 已提交
1562 1563 1564 1565 1566
		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";
1567

1568 1569
	if (!InitBasicConfig())
		throw "Failed to load basic.ini";
1570
	if (!ResetAudio())
1571 1572
		throw "Failed to initialize audio";

1573
	ret = ResetVideo();
1574 1575 1576 1577 1578

	switch (ret) {
	case OBS_VIDEO_MODULE_NOT_FOUND:
		throw "Failed to initialize video:  Graphics module not found";
	case OBS_VIDEO_NOT_SUPPORTED:
1579
		throw UNSUPPORTED_ERROR;
1580 1581 1582 1583
	case OBS_VIDEO_INVALID_PARAM:
		throw "Failed to initialize video:  Invalid parameters";
	default:
		if (ret != OBS_VIDEO_SUCCESS)
1584
			throw UNKNOWN_ERROR;
1585 1586
	}

1587
	/* load audio monitoring */
1588
#if defined(_WIN32) || defined(__APPLE__) || HAVE_PULSEAUDIO
J
jp9000 已提交
1589 1590 1591 1592
	const char *device_name =
		config_get_string(basicConfig, "Audio", "MonitoringDeviceName");
	const char *device_id =
		config_get_string(basicConfig, "Audio", "MonitoringDeviceId");
1593 1594

	obs_set_audio_monitoring_device(device_name, device_id);
1595 1596

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

1600
	InitOBSCallbacks();
P
Palana 已提交
1601
	InitHotkeys();
1602

1603
	AddExtraModulePaths();
1604
	blog(LOG_INFO, "---------------------------------");
J
jp9000 已提交
1605
	obs_load_all_modules();
1606 1607
	blog(LOG_INFO, "---------------------------------");
	obs_log_loaded_modules();
1608 1609
	blog(LOG_INFO, "---------------------------------");
	obs_post_load_modules();
J
jp9000 已提交
1610

1611
#ifdef BROWSER_AVAILABLE
J
jp9000 已提交
1612
	cef = obs_browser_init_panel();
J
jp9000 已提交
1613 1614
#endif

1615 1616
	InitBasicConfigDefaults2();

1617 1618
	CheckForSimpleModeX264Fallback();

1619
	blog(LOG_INFO, STARTUP_SEPARATOR);
1620

J
jp9000 已提交
1621
	ResetOutputs();
1622
	CreateHotkeys();
J
jp9000 已提交
1623

1624 1625 1626
	if (!InitService())
		throw "Failed to initialize service";

J
jp9000 已提交
1627 1628
	InitPrimitives();

J
jp9000 已提交
1629 1630 1631 1632 1633 1634
	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 已提交
1635

J
jp9000 已提交
1636 1637 1638 1639
#define SET_VISIBILITY(name, control)                                         \
	do {                                                                  \
		if (config_has_user_value(App()->GlobalConfig(),              \
					  "BasicWindow", name)) {             \
1640
			bool visible = config_get_bool(App()->GlobalConfig(), \
J
jp9000 已提交
1641 1642 1643
						       "BasicWindow", name);  \
			ui->control->setChecked(visible);                     \
		}                                                             \
1644 1645 1646 1647 1648 1649
	} while (false)

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

1650 1651 1652 1653
	bool sourceIconsVisible = config_get_bool(
		GetGlobalConfig(), "BasicWindow", "ShowSourceIcons");
	ui->toggleSourceIcons->setChecked(sourceIconsVisible);

1654 1655 1656 1657 1658 1659 1660
	{
		ProfileScope("OBSBasic::Load");
		disableSaving--;
		Load(savePath);
		disableSaving++;
	}

J
jp9000 已提交
1661
	TimedCheckForUpdates();
1662
	loaded = true;
J
jp9000 已提交
1663

J
jp9000 已提交
1664 1665
	previewEnabled = config_get_bool(App()->GlobalConfig(), "BasicWindow",
					 "PreviewEnabled");
1666 1667 1668

	if (!previewEnabled && !IsPreviewProgramMode())
		QMetaObject::invokeMethod(this, "EnablePreviewDisplay",
J
jp9000 已提交
1669 1670
					  Qt::QueuedConnection,
					  Q_ARG(bool, previewEnabled));
1671 1672 1673 1674

#ifdef _WIN32
	uint32_t winVer = GetWindowsVersion();
	if (winVer > 0 && winVer < 0x602) {
J
jp9000 已提交
1675 1676
		bool disableAero =
			config_get_bool(basicConfig, "Video", "DisableAero");
1677 1678 1679
		SetAeroEnabled(!disableAero);
	}
#endif
J
jp9000 已提交
1680

1681
	RefreshSceneCollections();
J
jp9000 已提交
1682
	RefreshProfiles();
J
jp9000 已提交
1683
	disableSaving--;
1684

J
jp9000 已提交
1685
	auto addDisplay = [this](OBSQTDisplay *window) {
1686
		obs_display_add_draw_callback(window->GetDisplay(),
J
jp9000 已提交
1687
					      OBSBasic::RenderMain, this);
1688 1689 1690 1691 1692 1693 1694 1695

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

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

1696
#ifdef _WIN32
J
jp9000 已提交
1697
	SetWin32DropStyle(this);
1698 1699 1700 1701
	show();
#endif

	bool alwaysOnTop = config_get_bool(App()->GlobalConfig(), "BasicWindow",
J
jp9000 已提交
1702
					   "AlwaysOnTop");
1703
	if (alwaysOnTop || opt_always_on_top) {
1704 1705 1706 1707 1708
		SetAlwaysOnTop(this, true);
		ui->actionAlwaysOnTop->setChecked(true);
	}

#ifndef _WIN32
1709
	show();
1710
#endif
J
jp9000 已提交
1711

A
Alex Anderson 已提交
1712
	/* setup stats dock */
1713 1714
	OBSBasicStats *statsDlg = new OBSBasicStats(statsDock, false);
	statsDock->setWidget(statsDlg);
A
Alex Anderson 已提交
1715

1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
	/* ----------------------------- */
	/* add custom browser docks      */

#ifdef BROWSER_AVAILABLE
	if (cef) {
		QAction *action = new QAction(QTStr("Basic.MainMenu."
						    "View.Docks."
						    "CustomBrowserDocks"));
		ui->viewMenuDocks->insertAction(ui->toggleScenes, action);
		connect(action, &QAction::triggered, this,
			&OBSBasic::ManageExtraBrowserDocks);
		ui->viewMenuDocks->insertSeparator(ui->toggleScenes);

		LoadExtraBrowserDocks();
	}
#endif

J
jp9000 已提交
1733 1734
	const char *dockStateStr = config_get_string(
		App()->GlobalConfig(), "BasicWindow", "DockState");
J
jp9000 已提交
1735 1736
	if (!dockStateStr) {
		on_resetUI_triggered();
J
jp9000 已提交
1737
	} else {
J
jp9000 已提交
1738 1739 1740 1741
		QByteArray dockState =
			QByteArray::fromBase64(QByteArray(dockStateStr));
		if (!restoreState(dockState))
			on_resetUI_triggered();
J
jp9000 已提交
1742 1743
	}

J
jp9000 已提交
1744 1745
	bool pre23Defaults = config_get_bool(App()->GlobalConfig(), "General",
					     "Pre23Defaults");
1746
	if (pre23Defaults) {
J
jp9000 已提交
1747 1748
		bool resetDockLock23 = config_get_bool(
			App()->GlobalConfig(), "General", "ResetDockLock23");
1749
		if (!resetDockLock23) {
J
jp9000 已提交
1750 1751
			config_set_bool(App()->GlobalConfig(), "General",
					"ResetDockLock23", true);
1752
			config_remove_value(App()->GlobalConfig(),
J
jp9000 已提交
1753
					    "BasicWindow", "DocksLocked");
1754 1755 1756
			config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
		}
	}
J
jp9000 已提交
1757

J
jp9000 已提交
1758 1759
	bool docksLocked = config_get_bool(App()->GlobalConfig(), "BasicWindow",
					   "DocksLocked");
J
jp9000 已提交
1760 1761 1762 1763
	on_lockUI_toggled(docksLocked);
	ui->lockUI->blockSignals(true);
	ui->lockUI->setChecked(docksLocked);
	ui->lockUI->blockSignals(false);
C
cg2121 已提交
1764

1765
#ifndef __APPLE__
C
cg2121 已提交
1766
	SystemTray(true);
1767
#endif
C
cg2121 已提交
1768

J
jp9000 已提交
1769
	bool has_last_version = config_has_user_value(App()->GlobalConfig(),
J
jp9000 已提交
1770 1771 1772
						      "General", "LastVersion");
	bool first_run =
		config_get_bool(App()->GlobalConfig(), "General", "FirstRun");
J
jp9000 已提交
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783

	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 已提交
1784 1785
		QMessageBox::StandardButton button = OBSMessageBox::question(
			this, QTStr("Basic.AutoConfig"), msg);
J
jp9000 已提交
1786 1787

		if (button == QMessageBox::Yes) {
J
jp9000 已提交
1788
			QMetaObject::invokeMethod(this,
J
jp9000 已提交
1789 1790
						  "on_autoConfigure_triggered",
						  Qt::QueuedConnection);
J
jp9000 已提交
1791 1792
		} else {
			msg = QTStr("Basic.FirstStartup.RunWizard.NoClicked");
J
jp9000 已提交
1793 1794
			OBSMessageBox::information(
				this, QTStr("Basic.AutoConfig"), msg);
J
jp9000 已提交
1795 1796
		}
	}
1797

1798
	ToggleMixerLayout(config_get_bool(App()->GlobalConfig(), "BasicWindow",
J
jp9000 已提交
1799
					  "VerticalVolControl"));
S
Shaolin 已提交
1800

1801 1802
	if (config_get_bool(basicConfig, "General", "OpenStatsOnStartup"))
		on_stats_triggered();
1803 1804

	OBSBasicStats::InitializeValues();
J
jp9000 已提交
1805 1806 1807 1808 1809 1810

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

	ui->viewMenu->addSeparator();

1811
	multiviewProjectorMenu = new QMenu(QTStr("MultiviewProjector"));
J
jp9000 已提交
1812
	ui->viewMenu->addMenu(multiviewProjectorMenu);
1813
	AddProjectorMenuMonitors(multiviewProjectorMenu, this,
J
jp9000 已提交
1814
				 SLOT(OpenMultiviewProjector()));
1815
	connect(ui->viewMenu->menuAction(), &QAction::hovered, this,
J
jp9000 已提交
1816 1817 1818
		&OBSBasic::UpdateMultiviewProjectorMenu);
	ui->viewMenu->addAction(QTStr("MultiviewWindowed"), this,
				SLOT(OpenMultiviewWindow()));
C
cg2121 已提交
1819

C
Clayton Groeneveld 已提交
1820 1821
	ui->sources->UpdateIcons();

1822 1823 1824 1825 1826 1827 1828 1829 1830
	if (!opt_studio_mode) {
		SetPreviewProgramMode(config_get_bool(App()->GlobalConfig(),
						      "BasicWindow",
						      "PreviewProgramMode"));
	} else {
		SetPreviewProgramMode(true);
		opt_studio_mode = false;
	}

C
cg2121 已提交
1831
#if !defined(_WIN32) && !defined(__APPLE__)
J
jp9000 已提交
1832 1833 1834
	delete ui->actionShowCrashLogs;
	delete ui->actionUploadLastCrashLog;
	delete ui->menuCrashLogs;
C
cg2121 已提交
1835
	delete ui->actionCheckForUpdates;
J
jp9000 已提交
1836 1837 1838
	ui->actionShowCrashLogs = nullptr;
	ui->actionUploadLastCrashLog = nullptr;
	ui->menuCrashLogs = nullptr;
C
cg2121 已提交
1839 1840
	ui->actionCheckForUpdates = nullptr;
#endif
1841

1842 1843
	OnFirstLoad();

1844
#ifdef __APPLE__
1845
	QMetaObject::invokeMethod(this, "DeferredSysTrayLoad",
J
jp9000 已提交
1846
				  Qt::QueuedConnection, Q_ARG(int, 10));
1847
#endif
1848 1849
}

1850 1851 1852 1853
void OBSBasic::OnFirstLoad()
{
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_FINISHED_LOADING);
J
jp9000 已提交
1854

1855
#if defined(BROWSER_AVAILABLE) && defined(_WIN32)
J
jp9000 已提交
1856
	/* Attempt to load init screen if available */
J
jp9000 已提交
1857
	if (cef) {
J
jp9000 已提交
1858 1859
		WhatsNewInfoThread *wnit = new WhatsNewInfoThread();
		if (wnit) {
J
jp9000 已提交
1860 1861
			connect(wnit, &WhatsNewInfoThread::Result, this,
				&OBSBasic::ReceivedIntroJson);
J
jp9000 已提交
1862 1863
		}
		if (wnit) {
1864
			introCheckThread.reset(wnit);
J
jp9000 已提交
1865 1866 1867 1868
			introCheckThread->start();
		}
	}
#endif
J
jp9000 已提交
1869 1870

	Auth::Load();
1871 1872
}

1873
void OBSBasic::DeferredSysTrayLoad(int requeueCount)
1874 1875
{
	if (--requeueCount > 0) {
1876
		QMetaObject::invokeMethod(this, "DeferredSysTrayLoad",
J
jp9000 已提交
1877 1878
					  Qt::QueuedConnection,
					  Q_ARG(int, requeueCount));
1879 1880 1881
		return;
	}

1882 1883 1884
	/* Minimizng to tray on initial startup does not work on mac
	 * unless it is done in the deferred load */
	SystemTray(true);
1885 1886
}

J
jp9000 已提交
1887 1888 1889
/* shows a "what's new" page on startup of new versions using CEF */
void OBSBasic::ReceivedIntroJson(const QString &text)
{
1890
#ifdef BROWSER_AVAILABLE
J
jp9000 已提交
1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
#ifdef _WIN32
	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();
1906
		int rc = item["RC"].int_value();
J
jp9000 已提交
1907 1908 1909 1910 1911

		int major = 0;
		int minor = 0;

		sscanf(version.c_str(), "%d.%d", &major, &minor);
1912 1913 1914 1915 1916
#if OBS_RELEASE_CANDIDATE > 0
		if (major == OBS_RELEASE_CANDIDATE_MAJOR &&
		    minor == OBS_RELEASE_CANDIDATE_MINOR &&
		    rc == OBS_RELEASE_CANDIDATE) {
#else
J
jp9000 已提交
1917
		if (major == LIBOBS_API_MAJOR_VER &&
J
jp9000 已提交
1918
		    minor == LIBOBS_API_MINOR_VER && rc == 0) {
1919
#endif
J
jp9000 已提交
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929
			info_url = url;
			info_increment = increment;
		}
	}

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

1930 1931
#if OBS_RELEASE_CANDIDATE > 0
	uint32_t lastVersion = config_get_int(App()->GlobalConfig(), "General",
J
jp9000 已提交
1932
					      "LastRCVersion");
1933
#else
J
jp9000 已提交
1934 1935
	uint32_t lastVersion =
		config_get_int(App()->GlobalConfig(), "General", "LastVersion");
1936
#endif
J
jp9000 已提交
1937 1938 1939

	int current_version_increment = -1;

1940 1941 1942
#if OBS_RELEASE_CANDIDATE > 0
	if (lastVersion < OBS_RELEASE_CANDIDATE_VER) {
#else
1943
	if ((lastVersion & ~0xFFFF) < (LIBOBS_API_VER & ~0xFFFF)) {
1944
#endif
J
jp9000 已提交
1945
		config_set_int(App()->GlobalConfig(), "General",
J
jp9000 已提交
1946
			       "InfoIncrement", -1);
J
jp9000 已提交
1947 1948
	} else {
		current_version_increment = config_get_int(
J
jp9000 已提交
1949
			App()->GlobalConfig(), "General", "InfoIncrement");
J
jp9000 已提交
1950 1951 1952 1953 1954 1955
	}

	if (info_increment <= current_version_increment) {
		return;
	}

J
jp9000 已提交
1956 1957
	config_set_int(App()->GlobalConfig(), "General", "InfoIncrement",
		       info_increment);
J
jp9000 已提交
1958

1959 1960 1961 1962 1963 1964 1965
	/* 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();
J
jp9000 已提交
1966
	ExecuteFuncSafeBlock([] { cef->wait_for_browser_init(); });
1967

J
jp9000 已提交
1968 1969 1970 1971
	QDialog *dlg = new QDialog(this);
	dlg->setAttribute(Qt::WA_DeleteOnClose, true);
	dlg->setWindowTitle("What's New");
	dlg->resize(700, 600);
J
jp9000 已提交
1972

1973 1974 1975 1976
	Qt::WindowFlags flags = dlg->windowFlags();
	Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint;
	dlg->setWindowFlags(flags & (~helpFlag));

J
jp9000 已提交
1977
	QCefWidget *cefWidget = cef->create_widget(nullptr, info_url);
J
jp9000 已提交
1978 1979 1980 1981
	if (!cefWidget) {
		return;
	}

J
jp9000 已提交
1982 1983
	connect(cefWidget, SIGNAL(titleChanged(const QString &)), dlg,
		SLOT(setWindowTitle(const QString &)));
J
jp9000 已提交
1984 1985

	QPushButton *close = new QPushButton(QTStr("Close"));
J
jp9000 已提交
1986
	connect(close, &QAbstractButton::clicked, dlg, &QDialog::accept);
J
jp9000 已提交
1987 1988 1989 1990 1991 1992

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

J
jp9000 已提交
1993
	QVBoxLayout *topLayout = new QVBoxLayout(dlg);
J
jp9000 已提交
1994 1995 1996
	topLayout->addWidget(cefWidget);
	topLayout->addLayout(bottomLayout);

J
jp9000 已提交
1997
	dlg->show();
J
jp9000 已提交
1998 1999 2000
#else
	UNUSED_PARAMETER(text);
#endif
2001 2002 2003
#else
	UNUSED_PARAMETER(text);
#endif
J
jp9000 已提交
2004 2005
}

2006 2007 2008 2009
void OBSBasic::UpdateMultiviewProjectorMenu()
{
	multiviewProjectorMenu->clear();
	AddProjectorMenuMonitors(multiviewProjectorMenu, this,
J
jp9000 已提交
2010
				 SLOT(OpenMultiviewProjector()));
2011 2012
}

P
Palana 已提交
2013 2014
void OBSBasic::InitHotkeys()
{
P
Palana 已提交
2015 2016
	ProfileScope("OBSBasic::InitHotkeys");

P
Palana 已提交
2017
	struct obs_hotkeys_translations t = {};
J
jp9000 已提交
2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
	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 已提交
2035
#ifdef _WIN32
J
jp9000 已提交
2036
	t.meta = Str("Hotkeys.Windows");
P
Palana 已提交
2037
#else
J
jp9000 已提交
2038
	t.meta = Str("Hotkeys.Super");
P
Palana 已提交
2039
#endif
J
jp9000 已提交
2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
	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 已提交
2057 2058 2059
	obs_hotkeys_set_translations(&t);

	obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"),
J
jp9000 已提交
2060 2061
						   Str("Push-to-mute"),
						   Str("Push-to-talk"));
P
Palana 已提交
2062

J
jp9000 已提交
2063 2064
	obs_hotkeys_set_sceneitem_hotkeys_translations(Str("SceneItemShow"),
						       Str("SceneItemHide"));
P
Palana 已提交
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076

	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 已提交
2077
	OBSBasic &basic = *static_cast<OBSBasic *>(data);
P
Palana 已提交
2078
	QMetaObject::invokeMethod(&basic, "ProcessHotkey",
J
jp9000 已提交
2079 2080
				  Q_ARG(obs_hotkey_id, id),
				  Q_ARG(bool, pressed));
P
Palana 已提交
2081 2082
}

2083 2084
void OBSBasic::CreateHotkeys()
{
P
Palana 已提交
2085 2086
	ProfileScope("OBSBasic::CreateHotkeys");

J
jp9000 已提交
2087 2088 2089
	auto LoadHotkeyData = [&](const char *name) -> OBSData {
		const char *info =
			config_get_string(basicConfig, "Hotkeys", name);
2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101
		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 已提交
2102
	auto LoadHotkey = [&](obs_hotkey_id id, const char *name) {
J
jp9000 已提交
2103 2104 2105 2106 2107 2108 2109
		obs_data_array_t *array =
			obs_data_get_array(LoadHotkeyData(name), "bindings");

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

2110
	auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0,
J
jp9000 已提交
2111
				  const char *name1) {
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121
		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 已提交
2122 2123 2124 2125 2126 2127 2128 2129 2130
#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;                                              \
2131 2132 2133
	}

	streamingHotkeys = obs_hotkey_pair_register_frontend(
J
jp9000 已提交
2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147
		"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 已提交
2148 2149 2150 2151 2152 2153
		if (basic.outputHandler->StreamingActive() && pressed) {
			basic.ForceStopStreaming();
		}
	};

	forceStreamingStopHotkey = obs_hotkey_register_frontend(
J
jp9000 已提交
2154 2155 2156
		"OBSBasic.ForceStopStreaming",
		Str("Basic.Main.ForceStopStreaming"), cb, this);
	LoadHotkey(forceStreamingStopHotkey, "OBSBasic.ForceStopStreaming");
J
jp9000 已提交
2157

2158
	recordingHotkeys = obs_hotkey_pair_register_frontend(
J
jp9000 已提交
2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169
		"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 已提交
2170

J
jp9000 已提交
2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181
	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 已提交
2182
	replayBufHotkeys = obs_hotkey_pair_register_frontend(
J
jp9000 已提交
2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193
		"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");
2194 2195

	togglePreviewHotkeys = obs_hotkey_pair_register_frontend(
J
jp9000 已提交
2196 2197 2198 2199 2200 2201 2202 2203 2204 2205
		"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");
2206
#undef MAKE_CALLBACK
2207

J
jp9000 已提交
2208 2209
	auto togglePreviewProgram = [](void *data, obs_hotkey_id,
				       obs_hotkey_t *, bool pressed) {
2210
		if (pressed)
J
jp9000 已提交
2211 2212 2213
			QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
						  "on_modeSwitch_clicked",
						  Qt::QueuedConnection);
2214 2215 2216
	};

	togglePreviewProgramHotkey = obs_hotkey_register_frontend(
J
jp9000 已提交
2217 2218 2219
		"OBSBasic.TogglePreviewProgram",
		Str("Basic.TogglePreviewProgramMode"), togglePreviewProgram,
		this);
2220 2221
	LoadHotkey(togglePreviewProgramHotkey, "OBSBasic.TogglePreviewProgram");

J
jp9000 已提交
2222 2223
	auto transition = [](void *data, obs_hotkey_id, obs_hotkey_t *,
			     bool pressed) {
2224
		if (pressed)
J
jp9000 已提交
2225 2226 2227
			QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
						  "TransitionClicked",
						  Qt::QueuedConnection);
2228 2229 2230
	};

	transitionHotkey = obs_hotkey_register_frontend(
J
jp9000 已提交
2231
		"OBSBasic.Transition", Str("Transition"), transition, this);
2232
	LoadHotkey(transitionHotkey, "OBSBasic.Transition");
C
Clayton Groeneveld 已提交
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245

	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");
2246 2247
}

J
jp9000 已提交
2248 2249 2250 2251
void OBSBasic::ClearHotkeys()
{
	obs_hotkey_pair_unregister(streamingHotkeys);
	obs_hotkey_pair_unregister(recordingHotkeys);
J
jp9000 已提交
2252
	obs_hotkey_pair_unregister(pauseHotkeys);
J
jp9000 已提交
2253
	obs_hotkey_pair_unregister(replayBufHotkeys);
2254
	obs_hotkey_pair_unregister(togglePreviewHotkeys);
J
jp9000 已提交
2255
	obs_hotkey_unregister(forceStreamingStopHotkey);
2256 2257
	obs_hotkey_unregister(togglePreviewProgramHotkey);
	obs_hotkey_unregister(transitionHotkey);
C
Clayton Groeneveld 已提交
2258
	obs_hotkey_unregister(statsHotkey);
J
jp9000 已提交
2259 2260
}

2261 2262
OBSBasic::~OBSBasic()
{
J
jp9000 已提交
2263 2264 2265
	if (updateCheckThread && updateCheckThread->isRunning())
		updateCheckThread->wait();

2266
	delete multiviewProjectorMenu;
P
pkv 已提交
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279
	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;
P
pkviet 已提交
2280
	delete trayMenu;
2281 2282
	delete programOptions;
	delete program;
J
jp9000 已提交
2283

J
jp9000 已提交
2284 2285 2286 2287 2288 2289
	/* 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 已提交
2290
	delete cpuUsageTimer;
2291 2292
	os_cpu_usage_info_destroy(cpuUsageInfo);

P
Palana 已提交
2293
	obs_hotkey_set_callback_routing_func(nullptr, nullptr);
J
jp9000 已提交
2294
	ClearHotkeys();
P
Palana 已提交
2295

2296
	service = nullptr;
J
jp9000 已提交
2297 2298
	outputHandler.reset();

J
John Bradley 已提交
2299 2300 2301
	if (interaction)
		delete interaction;

2302 2303 2304
	if (properties)
		delete properties;

J
jp9000 已提交
2305 2306 2307
	if (filters)
		delete filters;

2308 2309
	if (transformWindow)
		delete transformWindow;
2310

J
jp9000 已提交
2311 2312 2313
	if (advAudioWindow)
		delete advAudioWindow;

C
cg2121 已提交
2314 2315 2316
	if (about)
		delete about;

2317
	obs_display_remove_draw_callback(ui->preview->GetDisplay(),
J
jp9000 已提交
2318
					 OBSBasic::RenderMain, this);
2319

J
jp9000 已提交
2320
	obs_enter_graphics();
2321
	gs_vertexbuffer_destroy(box);
2322 2323 2324 2325
	gs_vertexbuffer_destroy(boxLeft);
	gs_vertexbuffer_destroy(boxTop);
	gs_vertexbuffer_destroy(boxRight);
	gs_vertexbuffer_destroy(boxBottom);
2326
	gs_vertexbuffer_destroy(circle);
J
jp9000 已提交
2327
	obs_leave_graphics();
J
jp9000 已提交
2328

2329 2330 2331 2332 2333 2334 2335 2336 2337
	/* 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 已提交
2338
	config_set_int(App()->GlobalConfig(), "General", "LastVersion",
J
jp9000 已提交
2339
		       LIBOBS_API_VER);
2340 2341
#if OBS_RELEASE_CANDIDATE > 0
	config_set_int(App()->GlobalConfig(), "General", "LastRCVersion",
J
jp9000 已提交
2342
		       OBS_RELEASE_CANDIDATE_VER);
2343
#endif
J
jp9000 已提交
2344

2345
	bool alwaysOnTop = IsAlwaysOnTop(this);
J
jp9000 已提交
2346

J
jp9000 已提交
2347 2348
	config_set_bool(App()->GlobalConfig(), "BasicWindow", "PreviewEnabled",
			previewEnabled);
2349 2350
	config_set_bool(App()->GlobalConfig(), "BasicWindow", "AlwaysOnTop",
			alwaysOnTop);
2351 2352
	config_set_bool(App()->GlobalConfig(), "BasicWindow",
			"SceneDuplicationMode", sceneDuplicationMode);
J
jp9000 已提交
2353 2354
	config_set_bool(App()->GlobalConfig(), "BasicWindow", "SwapScenesMode",
			swapScenesMode);
2355 2356 2357 2358
	config_set_bool(App()->GlobalConfig(), "BasicWindow",
			"EditPropertiesMode", editPropertiesMode);
	config_set_bool(App()->GlobalConfig(), "BasicWindow",
			"PreviewProgramMode", IsPreviewProgramMode());
J
jp9000 已提交
2359 2360
	config_set_bool(App()->GlobalConfig(), "BasicWindow", "DocksLocked",
			ui->lockUI->isChecked());
2361
	config_save_safe(App()->GlobalConfig(), "tmp", nullptr);
2362 2363 2364 2365

#ifdef _WIN32
	uint32_t winVer = GetWindowsVersion();
	if (winVer > 0 && winVer < 0x602) {
J
jp9000 已提交
2366 2367
		bool disableAero =
			config_get_bool(basicConfig, "Video", "DisableAero");
2368 2369 2370 2371 2372
		if (disableAero) {
			SetAeroEnabled(true);
		}
	}
#endif
J
jp9000 已提交
2373 2374

#ifdef BROWSER_AVAILABLE
2375
	DestroyPanelCookieManager();
J
jp9000 已提交
2376 2377 2378
	delete cef;
	cef = nullptr;
#endif
2379 2380
}

J
jp9000 已提交
2381 2382 2383 2384 2385 2386 2387 2388 2389
void OBSBasic::SaveProjectNow()
{
	if (disableSaving)
		return;

	projectChanged = true;
	SaveProjectDeferred();
}

J
jp9000 已提交
2390 2391
void OBSBasic::SaveProject()
{
J
jp9000 已提交
2392 2393 2394
	if (disableSaving)
		return;

J
jp9000 已提交
2395 2396
	projectChanged = true;
	QMetaObject::invokeMethod(this, "SaveProjectDeferred",
J
jp9000 已提交
2397
				  Qt::QueuedConnection);
J
jp9000 已提交
2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
}

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

	if (!projectChanged)
		return;

	projectChanged = false;

J
jp9000 已提交
2410 2411
	const char *sceneCollection = config_get_string(
		App()->GlobalConfig(), "Basic", "SceneCollectionFile");
2412
	char savePath[512];
J
jp9000 已提交
2413 2414 2415 2416 2417 2418 2419
	char fileName[512];
	int ret;

	if (!sceneCollection)
		return;

	ret = snprintf(fileName, 512, "obs-studio/basic/scenes/%s.json",
J
jp9000 已提交
2420
		       sceneCollection);
J
jp9000 已提交
2421 2422 2423 2424
	if (ret <= 0)
		return;

	ret = GetConfigPath(savePath, sizeof(savePath), fileName);
2425 2426 2427
	if (ret <= 0)
		return;

J
jp9000 已提交
2428 2429 2430
	Save(savePath);
}

S
Shaolin 已提交
2431 2432 2433 2434 2435
OBSSource OBSBasic::GetProgramSource()
{
	return OBSGetStrongRef(programScene);
}

J
jp9000 已提交
2436
OBSScene OBSBasic::GetCurrentScene()
2437
{
J
jp9000 已提交
2438
	QListWidgetItem *item = ui->scenes->currentItem();
P
Palana 已提交
2439
	return item ? GetOBSRef<OBSScene>(item) : nullptr;
2440 2441
}

2442
OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item)
J
jp9000 已提交
2443
{
P
Palana 已提交
2444
	return item ? GetOBSRef<OBSSceneItem>(item) : nullptr;
J
jp9000 已提交
2445 2446
}

2447 2448
OBSSceneItem OBSBasic::GetCurrentSceneItem()
{
J
jp9000 已提交
2449
	return ui->sources->Get(GetTopSelectedSourceItem());
2450 2451
}

J
Joseph El-Khouri 已提交
2452 2453
void OBSBasic::UpdatePreviewScalingMenu()
{
2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467
	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 已提交
2468 2469 2470
	ui->actionScaleOutput->setChecked(scalingAmount ==
					  float(ovi.output_width) /
						  float(ovi.base_width));
J
Joseph El-Khouri 已提交
2471 2472
}

2473
void OBSBasic::CreateInteractionWindow(obs_source_t *source)
J
John Bradley 已提交
2474 2475 2476 2477 2478 2479 2480 2481 2482
{
	if (interaction)
		interaction->close();

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

2483
void OBSBasic::CreatePropertiesWindow(obs_source_t *source)
2484 2485 2486 2487 2488 2489 2490
{
	if (properties)
		properties->close();

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

J
jp9000 已提交
2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
void OBSBasic::CreateFiltersWindow(obs_source_t *source)
{
	if (filters)
		filters->close();

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

2503 2504 2505
/* Qt callbacks for invokeMethod */

void OBSBasic::AddScene(OBSSource source)
2506
{
J
jp9000 已提交
2507
	const char *name = obs_source_get_name(source);
2508
	obs_scene_t *scene = obs_scene_from_source(source);
J
jp9000 已提交
2509 2510

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

J
jp9000 已提交
2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528
	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 已提交
2529

2530
	signal_handler_t *handler = obs_source_get_signal_handler(source);
2531

J
jp9000 已提交
2532 2533 2534
	SignalContainer<OBSScene> container;
	container.ref = scene;
	container.handlers.assign({
2535
		std::make_shared<OBSSignal>(handler, "item_add",
J
jp9000 已提交
2536
					    OBSBasic::SceneItemAdded, this),
2537
		std::make_shared<OBSSignal>(handler, "item_select",
J
jp9000 已提交
2538
					    OBSBasic::SceneItemSelected, this),
2539
		std::make_shared<OBSSignal>(handler, "item_deselect",
J
jp9000 已提交
2540 2541
					    OBSBasic::SceneItemDeselected,
					    this),
2542
		std::make_shared<OBSSignal>(handler, "reorder",
J
jp9000 已提交
2543
					    OBSBasic::SceneReordered, this),
2544 2545
		std::make_shared<OBSSignal>(handler, "refresh",
					    OBSBasic::SceneRefreshed, this),
J
jp9000 已提交
2546
	});
2547 2548

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

2551
	/* if the scene already has items (a duplicated scene) add them */
J
jp9000 已提交
2552
	auto addSceneItem = [this](obs_sceneitem_t *item) {
2553 2554 2555 2556 2557
		AddSceneItem(item);
	};

	using addSceneItem_t = decltype(addSceneItem);

J
jp9000 已提交
2558 2559 2560 2561 2562 2563 2564 2565 2566
	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);
2567

J
jp9000 已提交
2568
	SaveProject();
2569 2570 2571 2572

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

		OBSProjector::UpdateMultiviewProjectors();
2576
	}
2577 2578 2579

	if (api)
		api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
2580 2581
}

2582
void OBSBasic::RemoveScene(OBSSource source)
J
jp9000 已提交
2583
{
P
Palana 已提交
2584 2585 2586 2587
	obs_scene_t *scene = obs_scene_from_source(source);

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

P
Palana 已提交
2589 2590 2591 2592 2593
	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 已提交
2594

P
Palana 已提交
2595 2596 2597
		sel = item;
		break;
	}
J
jp9000 已提交
2598

J
jp9000 已提交
2599
	if (sel != nullptr) {
P
Palana 已提交
2600
		if (sel == ui->scenes->currentItem())
J
jp9000 已提交
2601
			ui->sources->Clear();
J
jp9000 已提交
2602
		delete sel;
J
jp9000 已提交
2603
	}
J
jp9000 已提交
2604 2605

	SaveProject();
2606 2607 2608

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

		OBSProjector::UpdateMultiviewProjectors();
2612
	}
2613 2614 2615

	if (api)
		api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
2616 2617
}

J
jp9000 已提交
2618 2619 2620
static bool select_one(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
{
	obs_sceneitem_t *selectedItem =
J
jp9000 已提交
2621
		reinterpret_cast<obs_sceneitem_t *>(param);
J
jp9000 已提交
2622 2623 2624 2625 2626 2627 2628 2629 2630
	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;
}

2631
void OBSBasic::AddSceneItem(OBSSceneItem item)
2632
{
J
jp9000 已提交
2633
	obs_scene_t *scene = obs_sceneitem_get_scene(item);
J
jp9000 已提交
2634

2635
	if (GetCurrentScene() == scene)
J
jp9000 已提交
2636
		ui->sources->Add(item);
J
jp9000 已提交
2637

J
jp9000 已提交
2638
	SaveProject();
2639 2640 2641 2642 2643

	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 已提交
2644 2645 2646 2647 2648 2649
		     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);
2650
	}
2651 2652
}

2653
void OBSBasic::UpdateSceneSelection(OBSSource source)
2654 2655
{
	if (source) {
2656
		obs_scene_t *scene = obs_scene_from_source(source);
2657
		const char *name = obs_source_get_name(source);
J
jp9000 已提交
2658

2659 2660 2661
		if (!scene)
			return;

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

2665 2666 2667 2668 2669
		if (items.count()) {
			sceneChanging = true;
			ui->scenes->setCurrentItem(items.first());
			sceneChanging = false;

2670 2671 2672
			OBSScene curScene =
				GetOBSRef<OBSScene>(ui->scenes->currentItem());
			if (api && scene != curScene)
J
jp9000 已提交
2673 2674
				api->on_event(
					OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
2675
		}
J
jp9000 已提交
2676
	}
2677 2678
}

J
jp9000 已提交
2679
static void RenameListValues(QListWidget *listWidget, const QString &newName,
J
jp9000 已提交
2680
			     const QString &prevName)
J
jp9000 已提交
2681
{
J
jp9000 已提交
2682
	QList<QListWidgetItem *> items =
J
jp9000 已提交
2683 2684 2685 2686 2687 2688
		listWidget->findItems(prevName, Qt::MatchExactly);

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

S
Shaolin 已提交
2689
void OBSBasic::RenameSources(OBSSource source, QString newName,
J
jp9000 已提交
2690
			     QString prevName)
J
jp9000 已提交
2691
{
J
jp9000 已提交
2692
	RenameListValues(ui->scenes, newName, prevName);
2693 2694 2695 2696 2697

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

2699 2700 2701 2702
	for (size_t i = 0; i < projectors.size(); i++) {
		if (projectors[i]->GetSource() == source)
			projectors[i]->RenameProjector(prevName, newName);
	}
C
cg2121 已提交
2703

J
jp9000 已提交
2704
	SaveProject();
S
Shaolin 已提交
2705 2706 2707 2708

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

2711 2712
void OBSBasic::SelectSceneItem(OBSScene scene, OBSSceneItem item, bool select)
{
J
jp9000 已提交
2713 2714
	SignalBlocker sourcesSignalBlocker(ui->sources);

2715
	if (scene != GetCurrentScene() || ignoreSelectionUpdate)
2716 2717
		return;

J
jp9000 已提交
2718
	ui->sources->SelectItem(item, select);
2719 2720
}

2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736
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);
}

2737 2738
void OBSBasic::GetAudioSourceFilters()
{
J
jp9000 已提交
2739 2740
	QAction *action = reinterpret_cast<QAction *>(sender());
	VolControl *vol = action->property("volControl").value<VolControl *>();
2741 2742 2743 2744 2745 2746 2747
	obs_source_t *source = vol->GetSource();

	CreateFiltersWindow(source);
}

void OBSBasic::GetAudioSourceProperties()
{
J
jp9000 已提交
2748 2749
	QAction *action = reinterpret_cast<QAction *>(sender());
	VolControl *vol = action->property("volControl").value<VolControl *>();
2750 2751 2752 2753 2754
	obs_source_t *source = vol->GetSource();

	CreatePropertiesWindow(source);
}

2755 2756
void OBSBasic::HideAudioControl()
{
J
jp9000 已提交
2757 2758
	QAction *action = reinterpret_cast<QAction *>(sender());
	VolControl *vol = action->property("volControl").value<VolControl *>();
2759 2760 2761 2762 2763 2764 2765 2766 2767 2768
	obs_source_t *source = vol->GetSource();

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

void OBSBasic::UnhideAllAudioControls()
{
J
jp9000 已提交
2769
	auto UnhideAudioMixer = [this](obs_source_t *source) /* -- */
2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782
	{
		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 已提交
2783 2784
	auto PreEnum = [](void *data, obs_source_t *source) -> bool /* -- */
	{ return (*reinterpret_cast<UnhideAudioMixer_t *>(data))(source); };
2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802

	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);
	}
}

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

	const char *prevName = obs_source_get_name(source);

	for (;;) {
		string name;
J
jp9000 已提交
2813 2814 2815 2816
		bool accepted = NameDialog::AskForName(
			this, QTStr("Basic.Main.MixerRename.Title"),
			QTStr("Basic.Main.MixerRename.Text"), name,
			QT_UTF8(prevName));
2817 2818 2819 2820
		if (!accepted)
			return;

		if (name.empty()) {
2821
			OBSMessageBox::warning(this,
J
jp9000 已提交
2822 2823
					       QTStr("NoNameEntered.Title"),
					       QTStr("NoNameEntered.Text"));
2824 2825 2826
			continue;
		}

2827 2828
		OBSSource sourceTest = obs_get_source_by_name(name.c_str());
		obs_source_release(sourceTest);
2829 2830

		if (sourceTest) {
J
jp9000 已提交
2831 2832
			OBSMessageBox::warning(this, QTStr("NameExists.Title"),
					       QTStr("NameExists.Text"));
2833 2834 2835 2836 2837 2838 2839 2840
			continue;
		}

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

2841 2842
void OBSBasic::VolControlContextMenu()
{
J
jp9000 已提交
2843
	VolControl *vol = reinterpret_cast<VolControl *>(sender());
2844

2845 2846 2847 2848
	/* ------------------- */

	QAction hideAction(QTStr("Hide"), this);
	QAction unhideAllAction(QTStr("UnhideAll"), this);
2849
	QAction mixerRenameAction(QTStr("Rename"), this);
2850

2851 2852 2853
	QAction copyFiltersAction(QTStr("Copy.Filters"), this);
	QAction pasteFiltersAction(QTStr("Paste.Filters"), this);

2854 2855
	QAction filtersAction(QTStr("Filters"), this);
	QAction propertiesAction(QTStr("Properties"), this);
2856
	QAction advPropAction(QTStr("Basic.MainMenu.Edit.AdvAudio"), this);
2857

S
Shaolin 已提交
2858 2859
	QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
	toggleControlLayoutAction.setCheckable(true);
J
jp9000 已提交
2860 2861
	toggleControlLayoutAction.setChecked(config_get_bool(
		GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
S
Shaolin 已提交
2862

2863 2864
	/* ------------------- */

J
jp9000 已提交
2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883
	connect(&hideAction, &QAction::triggered, this,
		&OBSBasic::HideAudioControl, Qt::DirectConnection);
	connect(&unhideAllAction, &QAction::triggered, this,
		&OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
	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);
2884

2885 2886
	/* ------------------- */

S
Shaolin 已提交
2887
	connect(&toggleControlLayoutAction, &QAction::changed, this,
J
jp9000 已提交
2888
		&OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
S
Shaolin 已提交
2889 2890 2891

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

2892
	hideAction.setProperty("volControl",
J
jp9000 已提交
2893
			       QVariant::fromValue<VolControl *>(vol));
2894
	mixerRenameAction.setProperty("volControl",
J
jp9000 已提交
2895
				      QVariant::fromValue<VolControl *>(vol));
2896

2897
	copyFiltersAction.setProperty("volControl",
J
jp9000 已提交
2898
				      QVariant::fromValue<VolControl *>(vol));
2899
	pasteFiltersAction.setProperty("volControl",
J
jp9000 已提交
2900
				       QVariant::fromValue<VolControl *>(vol));
2901

2902
	filtersAction.setProperty("volControl",
J
jp9000 已提交
2903
				  QVariant::fromValue<VolControl *>(vol));
2904
	propertiesAction.setProperty("volControl",
J
jp9000 已提交
2905
				     QVariant::fromValue<VolControl *>(vol));
2906

2907 2908
	/* ------------------- */

2909 2910 2911 2912 2913
	if (copyFiltersString == nullptr)
		pasteFiltersAction.setEnabled(false);
	else
		pasteFiltersAction.setEnabled(true);

2914
	QMenu popup;
2915 2916
	popup.addAction(&unhideAllAction);
	popup.addAction(&hideAction);
2917
	popup.addAction(&mixerRenameAction);
2918
	popup.addSeparator();
2919 2920 2921
	popup.addAction(&copyFiltersAction);
	popup.addAction(&pasteFiltersAction);
	popup.addSeparator();
S
Shaolin 已提交
2922 2923
	popup.addAction(&toggleControlLayoutAction);
	popup.addSeparator();
2924 2925
	popup.addAction(&filtersAction);
	popup.addAction(&propertiesAction);
2926
	popup.addAction(&advPropAction);
2927 2928 2929
	popup.exec(QCursor::pos());
}

S
Shaolin 已提交
2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940
void OBSBasic::on_hMixerScrollArea_customContextMenuRequested()
{
	StackedMixerAreaContextMenuRequested();
}

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

void OBSBasic::StackedMixerAreaContextMenuRequested()
2941 2942
{
	QAction unhideAllAction(QTStr("UnhideAll"), this);
S
SuslikV 已提交
2943 2944 2945

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

S
Shaolin 已提交
2946 2947
	QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this);
	toggleControlLayoutAction.setCheckable(true);
J
jp9000 已提交
2948 2949
	toggleControlLayoutAction.setChecked(config_get_bool(
		GetGlobalConfig(), "BasicWindow", "VerticalVolControl"));
S
Shaolin 已提交
2950

S
SuslikV 已提交
2951 2952
	/* ------------------- */

J
jp9000 已提交
2953 2954
	connect(&unhideAllAction, &QAction::triggered, this,
		&OBSBasic::UnhideAllAudioControls, Qt::DirectConnection);
2955

J
jp9000 已提交
2956 2957 2958
	connect(&advPropAction, &QAction::triggered, this,
		&OBSBasic::on_actionAdvAudioProperties_triggered,
		Qt::DirectConnection);
S
SuslikV 已提交
2959 2960 2961

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

S
Shaolin 已提交
2962
	connect(&toggleControlLayoutAction, &QAction::changed, this,
J
jp9000 已提交
2963
		&OBSBasic::ToggleVolControlLayout, Qt::DirectConnection);
S
Shaolin 已提交
2964 2965 2966

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

2967
	QMenu popup;
2968
	popup.addAction(&unhideAllAction);
S
SuslikV 已提交
2969
	popup.addSeparator();
S
Shaolin 已提交
2970 2971
	popup.addAction(&toggleControlLayoutAction);
	popup.addSeparator();
S
SuslikV 已提交
2972
	popup.addAction(&advPropAction);
2973 2974 2975
	popup.exec(QCursor::pos());
}

2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986
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 已提交
2987 2988 2989
void OBSBasic::ToggleVolControlLayout()
{
	bool vertical = !config_get_bool(GetGlobalConfig(), "BasicWindow",
J
jp9000 已提交
2990
					 "VerticalVolControl");
S
Shaolin 已提交
2991 2992
	config_set_bool(GetGlobalConfig(), "BasicWindow", "VerticalVolControl",
			vertical);
2993
	ToggleMixerLayout(vertical);
S
Shaolin 已提交
2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006

	// 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);
}

3007 3008
void OBSBasic::ActivateAudioSource(OBSSource source)
{
3009 3010
	if (SourceMixerHidden(source))
		return;
3011 3012
	if (!obs_source_audio_active(source))
		return;
3013

S
Shaolin 已提交
3014
	bool vertical = config_get_bool(GetGlobalConfig(), "BasicWindow",
J
jp9000 已提交
3015
					"VerticalVolControl");
S
Shaolin 已提交
3016
	VolControl *vol = new VolControl(source, true, vertical);
3017

J
jp9000 已提交
3018 3019
	double meterDecayRate =
		config_get_double(basicConfig, "Audio", "MeterDecayRate");
S
Shaolin 已提交
3020
	vol->SetMeterDecayRate(meterDecayRate);
3021

J
jp9000 已提交
3022 3023
	uint32_t peakMeterTypeIdx =
		config_get_uint(basicConfig, "Audio", "PeakMeterType");
3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039

	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);

3040 3041
	vol->setContextMenuPolicy(Qt::CustomContextMenu);

J
jp9000 已提交
3042 3043 3044 3045
	connect(vol, &QWidget::customContextMenuRequested, this,
		&OBSBasic::VolControlContextMenu);
	connect(vol, &VolControl::ConfigClicked, this,
		&OBSBasic::VolControlContextMenu);
3046

3047 3048 3049
	InsertQObjectByName(volumes, vol);

	for (auto volume : volumes) {
S
Shaolin 已提交
3050 3051 3052 3053
		if (vertical)
			ui->vVolControlLayout->addWidget(volume);
		else
			ui->hVolControlLayout->addWidget(volume);
3054
	}
3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067
}

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;
		}
	}
}

3068
bool OBSBasic::QueryRemoveSource(obs_source_t *source)
J
jp9000 已提交
3069
{
J
jp9000 已提交
3070
	if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE &&
3071
	    !obs_source_is_group(source)) {
3072 3073 3074
		int count = ui->scenes->count();

		if (count == 1) {
3075
			OBSMessageBox::information(this,
J
jp9000 已提交
3076 3077
						   QTStr("FinalScene.Title"),
						   QTStr("FinalScene.Text"));
3078 3079
			return false;
		}
3080 3081
	}

J
jp9000 已提交
3082
	const char *name = obs_source_get_name(source);
3083 3084 3085

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

3087
	QMessageBox remove_source(this);
3088
	remove_source.setText(text);
J
jp9000 已提交
3089 3090
	QAbstractButton *Yes =
		remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole);
J
Jkoan 已提交
3091 3092 3093 3094 3095 3096
	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();
3097
}
J
jp9000 已提交
3098

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

P
Palana 已提交
3101 3102 3103 3104 3105
#ifdef UPDATE_SPARKLE
void init_sparkle_updater(bool update_to_undeployed);
void trigger_sparkle_update();
#endif

J
jp9000 已提交
3106 3107
void OBSBasic::TimedCheckForUpdates()
{
J
jp9000 已提交
3108
	if (!config_get_bool(App()->GlobalConfig(), "General",
J
jp9000 已提交
3109
			     "EnableAutoUpdates"))
J
jp9000 已提交
3110 3111
		return;

P
Palana 已提交
3112 3113
#ifdef UPDATE_SPARKLE
	init_sparkle_updater(config_get_bool(App()->GlobalConfig(), "General",
J
jp9000 已提交
3114
					     "UpdateToUndeployed"));
3115
#elif _WIN32
J
jp9000 已提交
3116
	long long lastUpdate = config_get_int(App()->GlobalConfig(), "General",
J
jp9000 已提交
3117 3118 3119
					      "LastUpdateCheck");
	uint32_t lastVersion =
		config_get_int(App()->GlobalConfig(), "General", "LastVersion");
J
jp9000 已提交
3120 3121 3122 3123

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

J
jp9000 已提交
3127
	long long t = (long long)time(nullptr);
J
jp9000 已提交
3128 3129 3130
	long long secs = t - lastUpdate;

	if (secs > UPDATE_CHECK_INTERVAL)
J
jp9000 已提交
3131
		CheckForUpdates(false);
P
Palana 已提交
3132
#endif
J
jp9000 已提交
3133 3134
}

J
jp9000 已提交
3135
void OBSBasic::CheckForUpdates(bool manualUpdate)
J
jp9000 已提交
3136
{
P
Palana 已提交
3137 3138
#ifdef UPDATE_SPARKLE
	trigger_sparkle_update();
3139
#elif _WIN32
J
jp9000 已提交
3140 3141
	ui->actionCheckForUpdates->setEnabled(false);

J
jp9000 已提交
3142 3143
	if (updateCheckThread && updateCheckThread->isRunning())
		return;
3144

3145
	updateCheckThread.reset(new AutoUpdateThread(manualUpdate));
3146
	updateCheckThread->start();
P
Palana 已提交
3147
#endif
3148 3149

	UNUSED_PARAMETER(manualUpdate);
J
jp9000 已提交
3150 3151
}

J
jp9000 已提交
3152
void OBSBasic::updateCheckFinished()
J
jp9000 已提交
3153 3154 3155 3156
{
	ui->actionCheckForUpdates->setEnabled(true);
}

3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177
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 已提交
3178 3179 3180 3181
		bool accepted = NameDialog::AskForName(
			this, QTStr("Basic.Main.AddSceneDlg.Title"),
			QTStr("Basic.Main.AddSceneDlg.Text"), name,
			placeHolderText);
3182 3183 3184 3185
		if (!accepted)
			return;

		if (name.empty()) {
3186
			OBSMessageBox::warning(this,
J
jp9000 已提交
3187 3188
					       QTStr("NoNameEntered.Title"),
					       QTStr("NoNameEntered.Text"));
3189 3190 3191 3192 3193
			continue;
		}

		obs_source_t *source = obs_get_source_by_name(name.c_str());
		if (source) {
J
jp9000 已提交
3194 3195
			OBSMessageBox::warning(this, QTStr("NameExists.Title"),
					       QTStr("NameExists.Text"));
3196 3197 3198 3199 3200

			obs_source_release(source);
			continue;
		}

J
jp9000 已提交
3201 3202
		obs_scene_t *scene = obs_scene_duplicate(curScene, name.c_str(),
							 OBS_SCENE_DUP_REFS);
3203
		source = obs_scene_get_source(scene);
3204
		SetCurrentScene(source, true);
3205
		obs_scene_release(scene);
J
jp9000 已提交
3206

3207
		break;
3208 3209 3210
	}
}

3211 3212 3213 3214
void OBSBasic::RemoveSelectedScene()
{
	OBSScene scene = GetCurrentScene();
	if (scene) {
3215
		obs_source_t *source = obs_scene_get_source(scene);
J
jp9000 已提交
3216
		if (QueryRemoveSource(source)) {
3217
			obs_source_remove(source);
J
jp9000 已提交
3218 3219

			if (api)
J
jp9000 已提交
3220 3221
				api->on_event(
					OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);
J
jp9000 已提交
3222
		}
3223 3224 3225 3226 3227 3228 3229
	}
}

void OBSBasic::RemoveSelectedSceneItem()
{
	OBSSceneItem item = GetCurrentSceneItem();
	if (item) {
3230
		obs_source_t *source = obs_sceneitem_get_source(item);
3231
		if (QueryRemoveSource(source))
J
jp9000 已提交
3232 3233 3234 3235
			obs_sceneitem_remove(item);
	}
}

3236 3237
void OBSBasic::ReorderSources(OBSScene scene)
{
3238
	if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
3239 3240
		return;

J
jp9000 已提交
3241
	ui->sources->ReorderItems();
J
jp9000 已提交
3242
	SaveProject();
3243 3244
}

3245 3246 3247 3248 3249 3250 3251 3252 3253
void OBSBasic::RefreshSources(OBSScene scene)
{
	if (scene != GetCurrentScene() || ui->sources->IgnoreReorder())
		return;

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

3254 3255
/* OBS Callbacks */

3256 3257
void OBSBasic::SceneReordered(void *data, calldata_t *params)
{
J
jp9000 已提交
3258
	OBSBasic *window = static_cast<OBSBasic *>(data);
3259

J
jp9000 已提交
3260
	obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
3261 3262

	QMetaObject::invokeMethod(window, "ReorderSources",
J
jp9000 已提交
3263
				  Q_ARG(OBSScene, OBSScene(scene)));
3264 3265
}

3266 3267 3268 3269 3270 3271 3272 3273 3274 3275
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)));
}

3276
void OBSBasic::SceneItemAdded(void *data, calldata_t *params)
3277
{
J
jp9000 已提交
3278
	OBSBasic *window = static_cast<OBSBasic *>(data);
3279

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

3282
	QMetaObject::invokeMethod(window, "AddSceneItem",
J
jp9000 已提交
3283
				  Q_ARG(OBSSceneItem, OBSSceneItem(item)));
J
jp9000 已提交
3284 3285
}

3286 3287
void OBSBasic::SceneItemSelected(void *data, calldata_t *params)
{
J
jp9000 已提交
3288
	OBSBasic *window = static_cast<OBSBasic *>(data);
3289

J
jp9000 已提交
3290 3291
	obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
	obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
3292 3293

	QMetaObject::invokeMethod(window, "SelectSceneItem",
J
jp9000 已提交
3294 3295
				  Q_ARG(OBSScene, scene),
				  Q_ARG(OBSSceneItem, item), Q_ARG(bool, true));
3296 3297 3298 3299
}

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

J
jp9000 已提交
3302 3303
	obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene");
	obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item");
3304 3305

	QMetaObject::invokeMethod(window, "SelectSceneItem",
J
jp9000 已提交
3306 3307 3308
				  Q_ARG(OBSScene, scene),
				  Q_ARG(OBSSceneItem, item),
				  Q_ARG(bool, false));
3309 3310
}

3311
void OBSBasic::SourceCreated(void *data, calldata_t *params)
3312
{
J
jp9000 已提交
3313
	obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
3314

3315
	if (obs_scene_from_source(source) != NULL)
J
jp9000 已提交
3316 3317 3318
		QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
					  "AddScene", WaitConnection(),
					  Q_ARG(OBSSource, OBSSource(source)));
3319 3320
}

3321
void OBSBasic::SourceRemoved(void *data, calldata_t *params)
3322
{
J
jp9000 已提交
3323
	obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
3324

3325
	if (obs_scene_from_source(source) != NULL)
J
jp9000 已提交
3326 3327 3328
		QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
					  "RemoveScene",
					  Q_ARG(OBSSource, OBSSource(source)));
3329 3330
}

3331
void OBSBasic::SourceActivated(void *data, calldata_t *params)
3332
{
J
jp9000 已提交
3333 3334
	obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
	uint32_t flags = obs_source_get_output_flags(source);
3335 3336

	if (flags & OBS_SOURCE_AUDIO)
J
jp9000 已提交
3337 3338 3339
		QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
					  "ActivateAudioSource",
					  Q_ARG(OBSSource, OBSSource(source)));
3340 3341
}

3342
void OBSBasic::SourceDeactivated(void *data, calldata_t *params)
3343
{
J
jp9000 已提交
3344 3345
	obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
	uint32_t flags = obs_source_get_output_flags(source);
3346 3347

	if (flags & OBS_SOURCE_AUDIO)
J
jp9000 已提交
3348 3349 3350
		QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
					  "DeactivateAudioSource",
					  Q_ARG(OBSSource, OBSSource(source)));
3351 3352
}

3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370
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)));
}

3371
void OBSBasic::SourceRenamed(void *data, calldata_t *params)
J
jp9000 已提交
3372
{
J
jp9000 已提交
3373 3374
	obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source");
	const char *newName = calldata_string(params, "new_name");
J
jp9000 已提交
3375 3376
	const char *prevName = calldata_string(params, "prev_name");

J
jp9000 已提交
3377 3378 3379 3380
	QMetaObject::invokeMethod(static_cast<OBSBasic *>(data),
				  "RenameSources", Q_ARG(OBSSource, source),
				  Q_ARG(QString, QT_UTF8(newName)),
				  Q_ARG(QString, QT_UTF8(prevName)));
3381 3382

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

3385 3386 3387 3388 3389
void OBSBasic::DrawBackdrop(float cx, float cy)
{
	if (!box)
		return;

3390 3391
	GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawBackdrop");

J
jp9000 已提交
3392 3393 3394
	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");
3395 3396 3397

	vec4 colorVal;
	vec4_set(&colorVal, 0.0f, 0.0f, 0.0f, 1.0f);
3398
	gs_effect_set_vec4(color, &colorVal);
3399

3400 3401
	gs_technique_begin(tech);
	gs_technique_begin_pass(tech, 0);
3402 3403 3404 3405 3406 3407 3408 3409
	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();
3410 3411
	gs_technique_end_pass(tech);
	gs_technique_end(tech);
3412 3413

	gs_load_vertexbuffer(nullptr);
3414 3415

	GS_DEBUG_MARKER_END();
3416 3417
}

3418 3419
void OBSBasic::RenderMain(void *data, uint32_t cx, uint32_t cy)
{
3420 3421
	GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "RenderMain");

J
jp9000 已提交
3422
	OBSBasic *window = static_cast<OBSBasic *>(data);
3423 3424 3425 3426
	obs_video_info ovi;

	obs_get_video_info(&ovi);

J
jp9000 已提交
3427 3428
	window->previewCX = int(window->previewScale * float(ovi.base_width));
	window->previewCY = int(window->previewScale * float(ovi.base_height));
3429 3430 3431

	gs_viewport_push();
	gs_projection_push();
3432

3433 3434 3435
	obs_display_t *display = window->ui->preview->GetDisplay();
	uint32_t width, height;
	obs_display_size(display, &width, &height);
J
jp9000 已提交
3436
	float right = float(width) - window->previewX;
3437
	float bottom = float(height) - window->previewY;
3438

J
jp9000 已提交
3439 3440
	gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
		 100.0f);
3441 3442 3443

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

3444 3445
	/* --------------------------------------- */

3446
	gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height),
J
jp9000 已提交
3447 3448 3449
		 -100.0f, 100.0f);
	gs_set_viewport(window->previewX, window->previewY, window->previewCX,
			window->previewCY);
3450

3451
	if (window->IsPreviewProgramMode()) {
3452 3453 3454
		window->DrawBackdrop(float(ovi.base_width),
				     float(ovi.base_height));

3455 3456 3457 3458 3459
		OBSScene scene = window->GetCurrentScene();
		obs_source_t *source = obs_scene_get_source(scene);
		if (source)
			obs_source_video_render(source);
	} else {
3460
		obs_render_main_texture_src_color_only();
3461
	}
3462
	gs_load_vertexbuffer(nullptr);
3463

3464 3465
	/* --------------------------------------- */

J
jp9000 已提交
3466 3467
	gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f,
		 100.0f);
3468
	gs_reset_viewport();
J
jp9000 已提交
3469 3470 3471

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

3472 3473
	/* --------------------------------------- */

3474 3475
	gs_projection_pop();
	gs_viewport_pop();
J
jp9000 已提交
3476

3477 3478
	GS_DEBUG_MARKER_END();

J
jp9000 已提交
3479 3480
	UNUSED_PARAMETER(cx);
	UNUSED_PARAMETER(cy);
3481 3482
}

3483 3484
/* Main class functions */

3485
obs_service_t *OBSBasic::GetService()
3486
{
3487
	if (!service) {
J
jp9000 已提交
3488 3489
		service =
			obs_service_create("rtmp_common", NULL, NULL, nullptr);
3490 3491
		obs_service_release(service);
	}
3492 3493 3494
	return service;
}

3495
void OBSBasic::SetService(obs_service_t *newService)
3496
{
3497
	if (newService)
3498 3499 3500
		service = newService;
}

V
VodBox 已提交
3501 3502 3503 3504 3505
int OBSBasic::GetTransitionDuration()
{
	return ui->transitionDuration->value();
}

3506
bool OBSBasic::StreamingActive() const
3507 3508 3509 3510 3511 3512
{
	if (!outputHandler)
		return false;
	return outputHandler->StreamingActive();
}

3513 3514 3515 3516 3517 3518 3519
bool OBSBasic::Active() const
{
	if (!outputHandler)
		return false;
	return outputHandler->Active();
}

3520 3521 3522 3523 3524 3525
#ifdef _WIN32
#define IS_WIN32 1
#else
#define IS_WIN32 0
#endif

3526 3527
static inline int AttemptToResetVideo(struct obs_video_info *ovi)
{
3528
	return obs_reset_video(ovi);
3529 3530
}

3531 3532
static inline enum obs_scale_type GetScaleType(ConfigFile &basicConfig)
{
J
jp9000 已提交
3533 3534
	const char *scaleTypeStr =
		config_get_string(basicConfig, "Video", "ScaleType");
3535 3536 3537 3538 3539

	if (astrcmpi(scaleTypeStr, "bilinear") == 0)
		return OBS_SCALE_BILINEAR;
	else if (astrcmpi(scaleTypeStr, "lanczos") == 0)
		return OBS_SCALE_LANCZOS;
3540 3541
	else if (astrcmpi(scaleTypeStr, "area") == 0)
		return OBS_SCALE_AREA;
3542 3543 3544 3545
	else
		return OBS_SCALE_BICUBIC;
}

3546 3547 3548 3549 3550 3551
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 已提交
3552 3553
	else if (astrcmpi(name, "I444") == 0)
		return VIDEO_FORMAT_I444;
3554 3555 3556 3557 3558 3559 3560 3561 3562
#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 已提交
3563
		return VIDEO_FORMAT_RGBA;
3564 3565
}

3566 3567
void OBSBasic::ResetUI()
{
J
jp9000 已提交
3568 3569
	bool studioPortraitLayout = config_get_bool(
		GetGlobalConfig(), "BasicWindow", "StudioPortraitLayout");
3570

J
jp9000 已提交
3571 3572
	bool labels = config_get_bool(GetGlobalConfig(), "BasicWindow",
				      "StudioModeLabels");
3573

3574 3575 3576 3577
	if (studioPortraitLayout)
		ui->previewLayout->setDirection(QBoxLayout::TopToBottom);
	else
		ui->previewLayout->setDirection(QBoxLayout::LeftToRight);
3578 3579 3580 3581 3582 3583

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

	if (programLabel)
		programLabel->setHidden(!labels);
3584 3585
}

3586
int OBSBasic::ResetVideo()
J
jp9000 已提交
3587
{
3588 3589 3590
	if (outputHandler && outputHandler->Active())
		return OBS_VIDEO_CURRENTLY_ACTIVE;

P
Palana 已提交
3591 3592
	ProfileScope("OBSBasic::ResetVideo");

J
jp9000 已提交
3593
	struct obs_video_info ovi;
3594
	int ret;
J
jp9000 已提交
3595

3596
	GetConfigFPS(ovi.fps_num, ovi.fps_den);
J
jp9000 已提交
3597

J
jp9000 已提交
3598 3599 3600 3601 3602 3603
	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");
3604

J
jp9000 已提交
3605
	ovi.graphics_module = App()->GetRenderModule();
J
jp9000 已提交
3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620
	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 已提交
3621
	ovi.gpu_conversion = true;
J
jp9000 已提交
3622
	ovi.scale_type = GetScaleType(basicConfig);
3623

3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639
	if (ovi.base_width == 0 || ovi.base_height == 0) {
		ovi.base_width = 1920;
		ovi.base_height = 1080;
		config_set_uint(basicConfig, "Video", "BaseCX", 1920);
		config_set_uint(basicConfig, "Video", "BaseCY", 1080);
	}

	if (ovi.output_width == 0 || ovi.output_height == 0) {
		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);
	}

3640
	ret = AttemptToResetVideo(&ovi);
3641
	if (IS_WIN32 && ret != OBS_VIDEO_SUCCESS) {
3642 3643
		if (ret == OBS_VIDEO_CURRENTLY_ACTIVE) {
			blog(LOG_WARNING, "Tried to reset when "
J
jp9000 已提交
3644
					  "already active");
3645 3646 3647
			return ret;
		}

3648
		/* Try OpenGL if DirectX fails on windows */
3649
		if (astrcmpi(ovi.graphics_module, DL_OPENGL) != 0) {
J
jp9000 已提交
3650 3651 3652 3653 3654
			blog(LOG_WARNING,
			     "Failed to initialize obs video (%d) "
			     "with graphics_module='%s', retrying "
			     "with graphics_module='%s'",
			     ret, ovi.graphics_module, DL_OPENGL);
3655
			ovi.graphics_module = DL_OPENGL;
3656 3657
			ret = AttemptToResetVideo(&ovi);
		}
3658 3659
	} else if (ret == OBS_VIDEO_SUCCESS) {
		ResizePreview(ovi.base_width, ovi.base_height);
3660 3661
		if (program)
			ResizeProgram(ovi.base_width, ovi.base_height);
3662 3663
	}

3664
	if (ret == OBS_VIDEO_SUCCESS) {
3665
		OBSBasicStats::InitializeValues();
3666 3667
		OBSProjector::UpdateMultiviewProjectors();
	}
3668

3669
	return ret;
J
jp9000 已提交
3670
}
J
jp9000 已提交
3671

3672
bool OBSBasic::ResetAudio()
J
jp9000 已提交
3673
{
P
Palana 已提交
3674 3675
	ProfileScope("OBSBasic::ResetAudio");

3676
	struct obs_audio_info ai;
J
jp9000 已提交
3677 3678
	ai.samples_per_sec =
		config_get_uint(basicConfig, "Audio", "SampleRate");
3679

J
jp9000 已提交
3680 3681
	const char *channelSetupStr =
		config_get_string(basicConfig, "Audio", "ChannelSetup");
3682 3683 3684

	if (strcmp(channelSetupStr, "Mono") == 0)
		ai.speakers = SPEAKERS_MONO;
P
pkviet 已提交
3685 3686
	else if (strcmp(channelSetupStr, "2.1") == 0)
		ai.speakers = SPEAKERS_2POINT1;
P
pkviet 已提交
3687 3688
	else if (strcmp(channelSetupStr, "4.0") == 0)
		ai.speakers = SPEAKERS_4POINT0;
P
pkviet 已提交
3689 3690 3691 3692 3693 3694
	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;
3695 3696 3697
	else
		ai.speakers = SPEAKERS_STEREO;

J
jp9000 已提交
3698
	return obs_reset_audio(&ai);
J
jp9000 已提交
3699 3700
}

3701
void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId,
J
jp9000 已提交
3702
				const char *deviceDesc, int channel)
J
jp9000 已提交
3703
{
3704
	bool disable = deviceId && strcmp(deviceId, "disabled") == 0;
3705 3706
	obs_source_t *source;
	obs_data_t *settings;
J
jp9000 已提交
3707 3708 3709

	source = obs_get_output_source(channel);
	if (source) {
3710 3711 3712 3713
		if (disable) {
			obs_set_output_source(channel, nullptr);
		} else {
			settings = obs_source_get_settings(source);
J
jp9000 已提交
3714 3715
			const char *oldId =
				obs_data_get_string(settings, "device_id");
3716 3717
			if (strcmp(oldId, deviceId) != 0) {
				obs_data_set_string(settings, "device_id",
J
jp9000 已提交
3718
						    deviceId);
3719 3720 3721 3722
				obs_source_update(source, settings);
			}
			obs_data_release(settings);
		}
J
jp9000 已提交
3723 3724 3725

		obs_source_release(source);

3726 3727
	} else if (!disable) {
		settings = obs_data_create();
J
jp9000 已提交
3728
		obs_data_set_string(settings, "device_id", deviceId);
3729
		source = obs_source_create(sourceId, deviceDesc, settings,
J
jp9000 已提交
3730
					   nullptr);
J
jp9000 已提交
3731 3732 3733 3734 3735 3736 3737
		obs_data_release(settings);

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

J
jp9000 已提交
3738
void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy)
3739
{
J
jp9000 已提交
3740
	QSize targetSize;
3741
	bool isFixedScaling;
J
Joseph El-Khouri 已提交
3742
	obs_video_info ovi;
J
jp9000 已提交
3743

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

3747
	isFixedScaling = ui->preview->IsFixedScaling();
J
Joseph El-Khouri 已提交
3748 3749
	obs_get_video_info(&ovi);

3750 3751
	if (isFixedScaling) {
		previewScale = ui->preview->GetScalingAmount();
J
jp9000 已提交
3752 3753 3754 3755 3756
		GetCenterPosFromFixedScale(
			int(cx), int(cy),
			targetSize.width() - PREVIEW_EDGE_SIZE * 2,
			targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX,
			previewY, previewScale);
3757 3758
		previewX += ui->preview->GetScrollX();
		previewY += ui->preview->GetScrollY();
J
Joseph El-Khouri 已提交
3759 3760 3761

	} else {
		GetScaleAndCenterPos(int(cx), int(cy),
J
jp9000 已提交
3762 3763 3764 3765
				     targetSize.width() - PREVIEW_EDGE_SIZE * 2,
				     targetSize.height() -
					     PREVIEW_EDGE_SIZE * 2,
				     previewX, previewY, previewScale);
J
Joseph El-Khouri 已提交
3766
	}
J
jp9000 已提交
3767

3768 3769
	previewX += float(PREVIEW_EDGE_SIZE);
	previewY += float(PREVIEW_EDGE_SIZE);
J
jp9000 已提交
3770 3771
}

3772 3773
void OBSBasic::CloseDialogs()
{
J
jp9000 已提交
3774
	QList<QDialog *> childDialogs = this->findChildren<QDialog *>();
3775 3776 3777 3778 3779 3780
	if (!childDialogs.isEmpty()) {
		for (int i = 0; i < childDialogs.size(); ++i) {
			childDialogs.at(i)->close();
		}
	}

J
jp9000 已提交
3781 3782 3783 3784
	if (!stats.isNull())
		stats->close(); //call close to save Stats geometry
	if (!remux.isNull())
		remux->close();
3785 3786
}

3787 3788 3789 3790 3791 3792 3793
void OBSBasic::EnumDialogs()
{
	visDialogs.clear();
	modalDialogs.clear();
	visMsgBoxes.clear();

	/* fill list of Visible dialogs and Modal dialogs */
J
jp9000 已提交
3794
	QList<QDialog *> dialogs = findChildren<QDialog *>();
3795 3796 3797 3798 3799 3800 3801 3802
	for (QDialog *dialog : dialogs) {
		if (dialog->isVisible())
			visDialogs.append(dialog);
		if (dialog->isModal())
			modalDialogs.append(dialog);
	}

	/* fill list of Visible message boxes */
J
jp9000 已提交
3803
	QList<QMessageBox *> msgBoxes = findChildren<QMessageBox *>();
3804 3805 3806 3807 3808 3809
	for (QMessageBox *msgbox : msgBoxes) {
		if (msgbox->isVisible())
			visMsgBoxes.append(msgbox);
	}
}

3810 3811
void OBSBasic::ClearSceneData()
{
J
jp9000 已提交
3812 3813
	disableSaving++;

3814 3815 3816 3817
	CloseDialogs();

	ClearVolumeControls();
	ClearListItems(ui->scenes);
J
jp9000 已提交
3818
	ui->sources->Clear();
3819 3820
	ClearQuickTransitions();
	ui->transitions->clear();
3821

3822 3823 3824 3825 3826 3827 3828
	for (size_t i = 0; i < projectors.size(); i++) {
		if (projectors[i])
			delete projectors[i];
	}

	projectors.clear();

3829 3830 3831 3832 3833 3834
	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);
3835 3836 3837
	lastScene = nullptr;
	swapScene = nullptr;
	programScene = nullptr;
3838

J
jp9000 已提交
3839
	auto cb = [](void *unused, obs_source_t *source) {
3840 3841 3842 3843 3844 3845 3846
		obs_source_remove(source);
		UNUSED_PARAMETER(unused);
		return true;
	};

	obs_enum_sources(cb, nullptr);

3847 3848 3849
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);

J
jp9000 已提交
3850
	disableSaving--;
3851 3852 3853

	blog(LOG_INFO, "All scene data cleared");
	blog(LOG_INFO, "------------------------------------------------");
3854 3855
}

J
jp9000 已提交
3856
void OBSBasic::closeEvent(QCloseEvent *event)
J
jp9000 已提交
3857
{
3858 3859 3860 3861 3862 3863 3864 3865 3866
	/* 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;
	}

3867
	if (isVisible())
J
jp9000 已提交
3868 3869 3870
		config_set_string(App()->GlobalConfig(), "BasicWindow",
				  "geometry",
				  saveGeometry().toBase64().constData());
3871

3872
	if (outputHandler && outputHandler->Active()) {
C
cg2121 已提交
3873 3874
		SetShowing(true);

3875
		QMessageBox::StandardButton button = OBSMessageBox::question(
J
jp9000 已提交
3876 3877
			this, QTStr("ConfirmExit.Title"),
			QTStr("ConfirmExit.Text"));
3878 3879 3880 3881 3882 3883 3884

		if (button == QMessageBox::No) {
			event->ignore();
			return;
		}
	}

3885 3886 3887 3888
	QWidget::closeEvent(event);
	if (!event->isAccepted())
		return;

3889 3890
	blog(LOG_INFO, SHUTDOWN_SEPARATOR);

J
jp9000 已提交
3891 3892
	if (introCheckThread)
		introCheckThread->wait();
3893 3894 3895 3896 3897
	if (updateCheckThread)
		updateCheckThread->wait();
	if (logUploadThread)
		logUploadThread->wait();

P
Palana 已提交
3898 3899
	signalHandlers.clear();

J
jp9000 已提交
3900
	Auth::Save();
J
jp9000 已提交
3901
	SaveProjectNow();
J
jp9000 已提交
3902 3903
	auth.reset();

3904 3905
	delete extraBrowsers;

J
jp9000 已提交
3906 3907
	config_set_string(App()->GlobalConfig(), "BasicWindow", "DockState",
			  saveState().toBase64().constData());
J
jp9000 已提交
3908

3909 3910 3911 3912 3913
#ifdef BROWSER_AVAILABLE
	SaveExtraBrowserDocks();
	ClearExtraBrowserDocks();
#endif

J
jp9000 已提交
3914 3915 3916
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_EXIT);

J
jp9000 已提交
3917
	disableSaving++;
J
jp9000 已提交
3918

3919 3920 3921
	/* Clear all scene data (dialogs, widgets, widget sub-items, scenes,
	 * sources, etc) so that all references are released before shutdown */
	ClearSceneData();
3922 3923

	App()->quit();
3924 3925
}

J
jp9000 已提交
3926
void OBSBasic::changeEvent(QEvent *event)
3927
{
J
jp9000 已提交
3928 3929
	if (event->type() == QEvent::WindowStateChange && isMinimized() &&
	    trayIcon && trayIcon->isVisible() && sysTrayMinimizeToTray()) {
3930 3931 3932

		ToggleShowHide();
	}
3933 3934
}

3935 3936
void OBSBasic::on_actionShow_Recordings_triggered()
{
3937
	const char *mode = config_get_string(basicConfig, "Output", "Mode");
P
pkviet 已提交
3938
	const char *type = config_get_string(basicConfig, "AdvOut", "RecType");
J
jp9000 已提交
3939 3940 3941 3942 3943 3944 3945 3946 3947 3948
	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;
3949 3950 3951
	QDesktopServices::openUrl(QUrl::fromLocalFile(path));
}

P
Palana 已提交
3952 3953
void OBSBasic::on_actionRemux_triggered()
{
3954 3955 3956 3957 3958 3959
	if (!remux.isNull()) {
		remux->show();
		remux->raise();
		return;
	}

3960
	const char *mode = config_get_string(basicConfig, "Output", "Mode");
J
jp9000 已提交
3961 3962 3963 3964 3965 3966
	const char *path = strcmp(mode, "Advanced")
				   ? config_get_string(basicConfig,
						       "SimpleOutput",
						       "FilePath")
				   : config_get_string(basicConfig, "AdvOut",
						       "RecFilePath");
3967 3968 3969 3970 3971

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

P
Palana 已提交
3974 3975
void OBSBasic::on_action_Settings_triggered()
{
3976 3977 3978 3979 3980 3981 3982
	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 已提交
3983
				   SLOT(on_action_Settings_triggered()));
3984 3985 3986 3987 3988 3989 3990 3991 3992
		return;
	}

	if (settings_already_executing) {
		return;
	}

	settings_already_executing = true;

P
Palana 已提交
3993 3994
	OBSBasicSettings settings(this);
	settings.exec();
C
cg2121 已提交
3995
	SystemTray(false);
3996 3997

	settings_already_executing = false;
P
Palana 已提交
3998 3999
}

J
jp9000 已提交
4000 4001
void OBSBasic::on_actionAdvAudioProperties_triggered()
{
4002 4003 4004 4005 4006
	if (advAudioWindow != nullptr) {
		advAudioWindow->raise();
		return;
	}

4007 4008 4009
	bool iconsVisible = config_get_bool(App()->GlobalConfig(),
					    "BasicWindow", "ShowSourceIcons");

J
jp9000 已提交
4010 4011 4012
	advAudioWindow = new OBSBasicAdvAudio(this);
	advAudioWindow->show();
	advAudioWindow->setAttribute(Qt::WA_DeleteOnClose, true);
4013
	advAudioWindow->SetIconsVisible(iconsVisible);
4014

J
jp9000 已提交
4015 4016
	connect(advAudioWindow, SIGNAL(destroyed()), this,
		SLOT(on_advAudioProps_destroyed()));
J
jp9000 已提交
4017 4018
}

4019 4020 4021 4022 4023
void OBSBasic::on_advAudioProps_clicked()
{
	on_actionAdvAudioProperties_triggered();
}

4024 4025 4026 4027 4028
void OBSBasic::on_advAudioProps_destroyed()
{
	advAudioWindow = nullptr;
}

4029
void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current,
J
jp9000 已提交
4030
					    QListWidgetItem *prev)
4031
{
4032
	obs_source_t *source = NULL;
J
jp9000 已提交
4033

4034 4035 4036 4037
	if (sceneChanging)
		return;

	if (current) {
4038
		obs_scene_t *scene;
J
jp9000 已提交
4039

P
Palana 已提交
4040
		scene = GetOBSRef<OBSScene>(current);
4041
		source = obs_scene_get_source(scene);
4042 4043
	}

4044
	SetCurrentScene(source);
4045

4046 4047 4048
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);

4049
	UNUSED_PARAMETER(prev);
4050 4051
}

J
jp9000 已提交
4052 4053
void OBSBasic::EditSceneName()
{
4054
	QListWidgetItem *item = ui->scenes->currentItem();
J
jp9000 已提交
4055
	Qt::ItemFlags flags = item->flags();
4056 4057 4058 4059

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

4062 4063
void OBSBasic::AddProjectorMenuMonitors(QMenu *parent, QObject *target,
					const char *slot)
J
jp9000 已提交
4064 4065
{
	QAction *action;
J
jp9000 已提交
4066
	QList<QScreen *> screens = QGuiApplication::screens();
4067
	for (int i = 0; i < screens.size(); i++) {
4068
		QRect screenGeometry = screens[i]->geometry();
J
jp9000 已提交
4069 4070 4071 4072 4073 4074 4075
		QString str =
			QString("%1 %2: %3x%4 @ %5,%6")
				.arg(QTStr("Display"), QString::number(i + 1),
				     QString::number(screenGeometry.width()),
				     QString::number(screenGeometry.height()),
				     QString::number(screenGeometry.x()),
				     QString::number(screenGeometry.y()));
J
jp9000 已提交
4076 4077 4078 4079 4080 4081

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

J
jp9000 已提交
4082
void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos)
4083
{
J
jp9000 已提交
4084 4085
	QListWidgetItem *item = ui->scenes->itemAt(pos);

4086
	QMenu popup(this);
J
jp9000 已提交
4087
	QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this);
V
VodBox 已提交
4088

J
jp9000 已提交
4089 4090
	popup.addAction(QTStr("Add"), this,
			SLOT(on_actionAddScene_triggered()));
J
jp9000 已提交
4091

P
Palana 已提交
4092
	if (item) {
J
jp9000 已提交
4093 4094
		QAction *pasteFilters =
			new QAction(QTStr("Paste.Filters"), this);
4095 4096
		pasteFilters->setEnabled(copyFiltersString);
		connect(pasteFilters, SIGNAL(triggered()), this,
J
jp9000 已提交
4097
			SLOT(ScenePasteFilters()));
4098

P
Palana 已提交
4099
		popup.addSeparator();
J
jp9000 已提交
4100 4101 4102 4103
		popup.addAction(QTStr("Duplicate"), this,
				SLOT(DuplicateSelectedScene()));
		popup.addAction(QTStr("Copy.Filters"), this,
				SLOT(SceneCopyFilters()));
4104 4105
		popup.addAction(pasteFilters);
		popup.addSeparator();
J
jp9000 已提交
4106 4107 4108
		popup.addAction(QTStr("Rename"), this, SLOT(EditSceneName()));
		popup.addAction(QTStr("Remove"), this,
				SLOT(RemoveSelectedScene()));
J
jp9000 已提交
4109
		popup.addSeparator();
J
jp9000 已提交
4110

J
jp9000 已提交
4111 4112
		order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this,
				SLOT(on_actionSceneUp_triggered()));
J
jp9000 已提交
4113 4114 4115 4116 4117 4118 4119 4120 4121 4122
		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 已提交
4123

P
pkv 已提交
4124
		delete sceneProjectorMenu;
J
jp9000 已提交
4125 4126
		sceneProjectorMenu = new QMenu(QTStr("SceneProjector"));
		AddProjectorMenuMonitors(sceneProjectorMenu, this,
J
jp9000 已提交
4127
					 SLOT(OpenSceneProjector()));
J
jp9000 已提交
4128
		popup.addMenu(sceneProjectorMenu);
C
cg2121 已提交
4129 4130

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

		popup.addAction(sceneWindow);
J
jp9000 已提交
4134
		popup.addSeparator();
J
jp9000 已提交
4135 4136
		popup.addAction(QTStr("Filters"), this,
				SLOT(OpenSceneFilters()));
4137 4138 4139

		popup.addSeparator();

P
pkv 已提交
4140 4141 4142
		delete perSceneTransitionMenu;
		perSceneTransitionMenu = CreatePerSceneTransitionMenu();
		popup.addMenu(perSceneTransitionMenu);
S
Shaolin 已提交
4143 4144 4145

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

J
jp9000 已提交
4146 4147
		QAction *multiviewAction =
			popup.addAction(QTStr("ShowInMultiview"));
S
Shaolin 已提交
4148

J
jp9000 已提交
4149 4150 4151
		OBSSource source = GetCurrentSceneSource();
		OBSData data = obs_source_get_private_settings(source);
		obs_data_release(data);
S
Shaolin 已提交
4152

J
jp9000 已提交
4153
		obs_data_set_default_bool(data, "show_in_multiview", true);
J
jp9000 已提交
4154
		bool show = obs_data_get_bool(data, "show_in_multiview");
S
Shaolin 已提交
4155

J
jp9000 已提交
4156 4157
		multiviewAction->setCheckable(true);
		multiviewAction->setChecked(show);
S
Shaolin 已提交
4158

J
jp9000 已提交
4159 4160 4161 4162
		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 已提交
4163 4164 4165 4166
			OBSProjector::UpdateMultiviewProjectors();
		};

		connect(multiviewAction, &QAction::triggered,
J
jp9000 已提交
4167
			std::bind(showInMultiview, data));
P
Palana 已提交
4168
	}
J
jp9000 已提交
4169

V
VodBox 已提交
4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180
	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 已提交
4181
	popup.exec(QCursor::pos());
4182 4183
}

V
VodBox 已提交
4184 4185 4186 4187 4188 4189
void OBSBasic::on_actionGridMode_triggered()
{
	bool gridMode = !ui->scenes->GetGridMode();
	ui->scenes->SetGridMode(gridMode);
}

J
jp9000 已提交
4190
void OBSBasic::on_actionAddScene_triggered()
4191
{
4192
	string name;
S
Socapex 已提交
4193
	QString format{QTStr("Basic.Main.DefaultSceneName.Text")};
P
Palana 已提交
4194

4195
	int i = 2;
P
Palana 已提交
4196
	QString placeHolderText = format.arg(i);
4197
	obs_source_t *source = nullptr;
P
Palana 已提交
4198 4199
	while ((source = obs_get_source_by_name(QT_TO_UTF8(placeHolderText)))) {
		obs_source_release(source);
P
Palana 已提交
4200
		placeHolderText = format.arg(++i);
P
Palana 已提交
4201
	}
S
Socapex 已提交
4202

J
jp9000 已提交
4203 4204 4205
	bool accepted = NameDialog::AskForName(
		this, QTStr("Basic.Main.AddSceneDlg.Title"),
		QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText);
4206

J
jp9000 已提交
4207
	if (accepted) {
J
jp9000 已提交
4208
		if (name.empty()) {
4209
			OBSMessageBox::warning(this,
J
jp9000 已提交
4210 4211
					       QTStr("NoNameEntered.Title"),
					       QTStr("NoNameEntered.Text"));
J
jp9000 已提交
4212 4213 4214 4215
			on_actionAddScene_triggered();
			return;
		}

4216
		obs_source_t *source = obs_get_source_by_name(name.c_str());
4217
		if (source) {
J
jp9000 已提交
4218 4219
			OBSMessageBox::warning(this, QTStr("NameExists.Title"),
					       QTStr("NameExists.Text"));
4220 4221

			obs_source_release(source);
J
jp9000 已提交
4222
			on_actionAddScene_triggered();
4223 4224 4225
			return;
		}

4226
		obs_scene_t *scene = obs_scene_create(name.c_str());
4227
		source = obs_scene_get_source(scene);
4228
		SetCurrentScene(source);
4229
		obs_scene_release(scene);
4230
	}
4231 4232
}

J
jp9000 已提交
4233
void OBSBasic::on_actionRemoveScene_triggered()
4234
{
J
jp9000 已提交
4235
	OBSScene scene = GetCurrentScene();
4236
	obs_source_t *source = obs_scene_get_source(scene);
4237 4238 4239

	if (source && QueryRemoveSource(source))
		obs_source_remove(source);
4240 4241
}

J
jp9000 已提交
4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259
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;
4260 4261

	OBSProjector::UpdateMultiviewProjectors();
J
jp9000 已提交
4262 4263
}

J
jp9000 已提交
4264
void OBSBasic::on_actionSceneUp_triggered()
4265
{
J
jp9000 已提交
4266
	ChangeSceneIndex(true, -1, 0);
4267 4268
}

J
jp9000 已提交
4269
void OBSBasic::on_actionSceneDown_triggered()
4270
{
J
jp9000 已提交
4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281
	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 已提交
4282
			 ui->scenes->count() - 1);
4283 4284
}

J
jp9000 已提交
4285 4286
void OBSBasic::EditSceneItemName()
{
J
jp9000 已提交
4287 4288
	int idx = GetTopSelectedSourceItem();
	ui->sources->Edit(idx);
J
jp9000 已提交
4289 4290
}

J
jp9000 已提交
4291 4292
void OBSBasic::SetDeinterlacingMode()
{
J
jp9000 已提交
4293
	QAction *action = reinterpret_cast<QAction *>(sender());
J
jp9000 已提交
4294 4295 4296 4297 4298 4299 4300 4301 4302 4303
	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 已提交
4304
	QAction *action = reinterpret_cast<QAction *>(sender());
J
jp9000 已提交
4305 4306 4307 4308 4309 4310 4311 4312
	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 已提交
4313
QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source)
J
jp9000 已提交
4314 4315 4316 4317 4318 4319 4320
{
	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 已提交
4321 4322 4323 4324 4325
#define ADD_MODE(name, mode)                                    \
	action = menu->addAction(QTStr("" name), this,          \
				 SLOT(SetDeinterlacingMode())); \
	action->setProperty("mode", (int)mode);                 \
	action->setCheckable(true);                             \
J
jp9000 已提交
4326 4327
	action->setChecked(deinterlaceMode == mode);

J
jp9000 已提交
4328 4329 4330 4331 4332 4333
	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 已提交
4334
	ADD_MODE("Deinterlacing.Linear2x", OBS_DEINTERLACE_MODE_LINEAR_2X);
J
jp9000 已提交
4335 4336
	ADD_MODE("Deinterlacing.Yadif", OBS_DEINTERLACE_MODE_YADIF);
	ADD_MODE("Deinterlacing.Yadif2x", OBS_DEINTERLACE_MODE_YADIF_2X);
J
jp9000 已提交
4337 4338 4339 4340
#undef ADD_MODE

	menu->addSeparator();

J
jp9000 已提交
4341
#define ADD_ORDER(name, order)                                       \
J
jp9000 已提交
4342
	action = menu->addAction(QTStr("Deinterlacing." name), this, \
J
jp9000 已提交
4343 4344 4345
				 SLOT(SetDeinterlacingOrder()));     \
	action->setProperty("order", (int)order);                    \
	action->setCheckable(true);                                  \
J
jp9000 已提交
4346 4347
	action->setChecked(deinterlaceOrder == order);

J
jp9000 已提交
4348
	ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP);
J
jp9000 已提交
4349 4350 4351 4352 4353 4354
	ADD_ORDER("BottomFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_BOTTOM);
#undef ADD_ORDER

	return menu;
}

4355 4356
void OBSBasic::SetScaleFilter()
{
J
jp9000 已提交
4357
	QAction *action = reinterpret_cast<QAction *>(sender());
4358 4359 4360 4361 4362 4363
	obs_scale_type mode = (obs_scale_type)action->property("mode").toInt();
	OBSSceneItem sceneItem = GetCurrentSceneItem();

	obs_sceneitem_set_scale_filter(sceneItem, mode);
}

P
pkv 已提交
4364
QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item)
4365 4366 4367 4368
{
	obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item);
	QAction *action;

J
jp9000 已提交
4369 4370 4371 4372 4373
#define ADD_MODE(name, mode)                                                   \
	action =                                                               \
		menu->addAction(QTStr("" name), this, SLOT(SetScaleFilter())); \
	action->setProperty("mode", (int)mode);                                \
	action->setCheckable(true);                                            \
4374 4375
	action->setChecked(scaleFilter == mode);

J
jp9000 已提交
4376 4377
	ADD_MODE("Disable", OBS_SCALE_DISABLE);
	ADD_MODE("ScaleFiltering.Point", OBS_SCALE_POINT);
4378
	ADD_MODE("ScaleFiltering.Bilinear", OBS_SCALE_BILINEAR);
J
jp9000 已提交
4379 4380 4381
	ADD_MODE("ScaleFiltering.Bicubic", OBS_SCALE_BICUBIC);
	ADD_MODE("ScaleFiltering.Lanczos", OBS_SCALE_LANCZOS);
	ADD_MODE("ScaleFiltering.Area", OBS_SCALE_AREA);
4382 4383 4384 4385 4386
#undef ADD_MODE

	return menu;
}

J
jp9000 已提交
4387 4388 4389 4390
QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu,
					QWidgetAction *widgetAction,
					ColorSelect *select,
					obs_sceneitem_t *item)
4391 4392 4393 4394
{
	QAction *action;

	menu->setStyleSheet(QString(
J
jp9000 已提交
4395 4396 4397 4398 4399 4400 4401
		"*[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%);}"
4402 4403 4404 4405 4406 4407 4408 4409
		"*[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 已提交
4410
	action = menu->addAction(QTStr("Clear"), this, +SLOT(ColorChange()));
4411 4412 4413 4414 4415
	action->setCheckable(true);
	action->setProperty("bgColor", 0);
	action->setChecked(preset == 0);

	action = menu->addAction(QTStr("CustomColor"), this,
J
jp9000 已提交
4416
				 +SLOT(ColorChange()));
4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427
	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 已提交
4428 4429
		QPushButton *colorButton =
			select->findChild<QPushButton *>(button.str().c_str());
4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442
		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 已提交
4443
ColorSelect::ColorSelect(QWidget *parent)
J
jp9000 已提交
4444
	: QWidget(parent), ui(new Ui::ColorSelect)
P
pkv 已提交
4445 4446 4447 4448
{
	ui->setupUi(this);
}

J
jp9000 已提交
4449
void OBSBasic::CreateSourcePopupMenu(int idx, bool preview)
4450
{
4451
	QMenu popup(this);
P
pkv 已提交
4452 4453 4454 4455 4456 4457 4458
	delete previewProjectorSource;
	delete sourceProjector;
	delete scaleFilteringMenu;
	delete colorMenu;
	delete colorWidgetAction;
	delete colorSelect;
	delete deinterlaceMenu;
J
jp9000 已提交
4459 4460 4461

	if (preview) {
		QAction *action = popup.addAction(
J
jp9000 已提交
4462 4463
			QTStr("Basic.Main.PreviewConextMenu.Enable"), this,
			SLOT(TogglePreview()));
J
jp9000 已提交
4464
		action->setCheckable(true);
4465
		action->setChecked(
J
jp9000 已提交
4466
			obs_display_enabled(ui->preview->GetDisplay()));
4467 4468
		if (IsPreviewProgramMode())
			action->setEnabled(false);
J
jp9000 已提交
4469

J
Joseph El-Khouri 已提交
4470 4471
		popup.addAction(ui->actionLockPreview);
		popup.addMenu(ui->scalingMenu);
J
jp9000 已提交
4472

P
pkv 已提交
4473 4474
		previewProjectorSource = new QMenu(QTStr("PreviewProjector"));
		AddProjectorMenuMonitors(previewProjectorSource, this,
J
jp9000 已提交
4475
					 SLOT(OpenPreviewProjector()));
J
jp9000 已提交
4476

P
pkv 已提交
4477
		popup.addMenu(previewProjectorSource);
J
jp9000 已提交
4478

J
jp9000 已提交
4479 4480 4481
		QAction *previewWindow =
			popup.addAction(QTStr("PreviewWindow"), this,
					SLOT(OpenPreviewWindow()));
C
cg2121 已提交
4482 4483 4484

		popup.addAction(previewWindow);

J
jp9000 已提交
4485 4486 4487
		popup.addSeparator();
	}

J
jp9000 已提交
4488 4489 4490 4491
	QPointer<QMenu> addSourceMenu = CreateAddSourcePopupMenu();
	if (addSourceMenu)
		popup.addMenu(addSourceMenu);

4492
	ui->actionCopyFilters->setEnabled(false);
4493
	ui->actionCopySource->setEnabled(false);
4494

J
jp9000 已提交
4495 4496
	if (ui->sources->MultipleBaseSelected()) {
		popup.addSeparator();
J
jp9000 已提交
4497 4498
		popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources,
				SLOT(GroupSelectedItems()));
J
jp9000 已提交
4499 4500 4501

	} else if (ui->sources->GroupsSelected()) {
		popup.addSeparator();
J
jp9000 已提交
4502 4503
		popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources,
				SLOT(UngroupSelectedGroups()));
J
jp9000 已提交
4504 4505
	}

4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516
	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 已提交
4517
	if (idx != -1) {
J
jp9000 已提交
4518 4519 4520
		if (addSourceMenu)
			popup.addSeparator();

J
jp9000 已提交
4521
		OBSSceneItem sceneItem = ui->sources->Get(idx);
4522
		obs_source_t *source = obs_sceneitem_get_source(sceneItem);
J
jp9000 已提交
4523 4524
		uint32_t flags = obs_source_get_output_flags(source);
		bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) ==
J
jp9000 已提交
4525 4526
				    OBS_SOURCE_ASYNC_VIDEO;
		bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO;
J
John Bradley 已提交
4527 4528
		QAction *action;

P
pkv 已提交
4529 4530 4531
		colorMenu = new QMenu(QTStr("ChangeBG"));
		colorWidgetAction = new QWidgetAction(colorMenu);
		colorSelect = new ColorSelect(colorMenu);
J
jp9000 已提交
4532 4533
		popup.addMenu(AddBackgroundColorMenu(
			colorMenu, colorWidgetAction, colorSelect, sceneItem));
J
jp9000 已提交
4534 4535
		popup.addAction(QTStr("Rename"), this,
				SLOT(EditSceneItemName()));
4536
		popup.addAction(QTStr("Remove"), this,
4537
				SLOT(on_actionRemoveSource_triggered()));
J
jp9000 已提交
4538 4539
		popup.addSeparator();
		popup.addMenu(ui->orderMenu);
J
jp9000 已提交
4540
		popup.addMenu(ui->transformMenu);
J
jp9000 已提交
4541 4542 4543

		sourceProjector = new QMenu(QTStr("SourceProjector"));
		AddProjectorMenuMonitors(sourceProjector, this,
J
jp9000 已提交
4544
					 SLOT(OpenSourceProjector()));
J
jp9000 已提交
4545

C
cg2121 已提交
4546
		QAction *sourceWindow = popup.addAction(
J
jp9000 已提交
4547
			QTStr("SourceWindow"), this, SLOT(OpenSourceWindow()));
C
cg2121 已提交
4548 4549 4550

		popup.addAction(sourceWindow);

J
jp9000 已提交
4551
		popup.addSeparator();
4552 4553

		if (hasAudio) {
J
jp9000 已提交
4554 4555 4556
			QAction *actionHideMixer =
				popup.addAction(QTStr("HideMixer"), this,
						SLOT(ToggleHideMixer()));
4557 4558 4559 4560
			actionHideMixer->setCheckable(true);
			actionHideMixer->setChecked(SourceMixerHidden(source));
		}

J
jp9000 已提交
4561
		if (isAsyncVideo) {
P
pkv 已提交
4562
			deinterlaceMenu = new QMenu(QTStr("Deinterlacing"));
J
jp9000 已提交
4563 4564
			popup.addMenu(
				AddDeinterlacingMenu(deinterlaceMenu, source));
J
jp9000 已提交
4565 4566
			popup.addSeparator();
		}
4567

J
jp9000 已提交
4568 4569 4570
		QAction *resizeOutput =
			popup.addAction(QTStr("ResizeOutputSizeOfSource"), this,
					SLOT(ResizeOutputSizeOfSource()));
4571 4572 4573 4574

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

4575
		resizeOutput->setEnabled(!obs_video_active());
4576 4577 4578 4579

		if (width == 0 || height == 0)
			resizeOutput->setEnabled(false);

P
pkv 已提交
4580
		scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering"));
J
jp9000 已提交
4581 4582
		popup.addMenu(
			AddScaleFilteringMenu(scaleFilteringMenu, sceneItem));
4583 4584
		popup.addSeparator();

J
jp9000 已提交
4585
		popup.addMenu(sourceProjector);
C
cg2121 已提交
4586
		popup.addAction(sourceWindow);
J
jp9000 已提交
4587
		popup.addSeparator();
J
John Bradley 已提交
4588 4589

		action = popup.addAction(QTStr("Interact"), this,
J
jp9000 已提交
4590
					 SLOT(on_actionInteract_triggered()));
J
John Bradley 已提交
4591 4592

		action->setEnabled(obs_source_get_output_flags(source) &
J
jp9000 已提交
4593
				   OBS_SOURCE_INTERACTION);
J
John Bradley 已提交
4594

J
jp9000 已提交
4595
		popup.addAction(QTStr("Filters"), this, SLOT(OpenFilters()));
J
jp9000 已提交
4596 4597
		popup.addAction(QTStr("Properties"), this,
				SLOT(on_actionSourceProperties_triggered()));
4598 4599

		ui->actionCopyFilters->setEnabled(true);
4600
		ui->actionCopySource->setEnabled(true);
4601 4602
	} else {
		ui->actionPasteFilters->setEnabled(false);
J
jp9000 已提交
4603 4604 4605
	}

	popup.exec(QCursor::pos());
4606 4607
}

J
jp9000 已提交
4608 4609
void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos)
{
J
jp9000 已提交
4610 4611 4612 4613
	if (ui->scenes->count()) {
		QModelIndex idx = ui->sources->indexAt(pos);
		CreateSourcePopupMenu(idx.row(), false);
	}
P
Palana 已提交
4614 4615
}

4616 4617 4618 4619 4620 4621
void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem)
{
	if (!witem)
		return;

	if (IsPreviewProgramMode()) {
J
jp9000 已提交
4622 4623 4624
		bool doubleClickSwitch =
			config_get_bool(App()->GlobalConfig(), "BasicWindow",
					"TransitionOnDoubleClick");
4625

4626 4627
		if (doubleClickSwitch)
			TransitionClicked();
4628 4629 4630
	}
}

J
jp9000 已提交
4631
void OBSBasic::AddSource(const char *id)
4632
{
4633 4634 4635
	if (id && *id) {
		OBSBasicSourceSelect sourceSelect(this, id);
		sourceSelect.exec();
4636
		if (sourceSelect.newSource && strcmp(id, "group") != 0)
4637
			CreatePropertiesWindow(sourceSelect.newSource);
4638
	}
4639 4640
}

4641
QMenu *OBSBasic::CreateAddSourcePopupMenu()
4642
{
4643
	const char *type;
J
jp9000 已提交
4644
	bool foundValues = false;
4645
	bool foundDeprecated = false;
J
jp9000 已提交
4646
	size_t idx = 0;
4647

4648
	QMenu *popup = new QMenu(QTStr("Add"), this);
4649
	QMenu *deprecated = new QMenu(QTStr("Deprecated"), popup);
4650

J
jp9000 已提交
4651 4652
	auto getActionAfter = [](QMenu *menu, const QString &name) {
		QList<QAction *> actions = menu->actions();
J
jp9000 已提交
4653 4654 4655 4656 4657 4658

		for (QAction *menuAction : actions) {
			if (menuAction->text().compare(name) >= 0)
				return menuAction;
		}

J
jp9000 已提交
4659
		return (QAction *)nullptr;
J
jp9000 已提交
4660 4661
	};

J
jp9000 已提交
4662 4663
	auto addSource = [this, getActionAfter](QMenu *popup, const char *type,
						const char *name) {
J
jp9000 已提交
4664 4665
		QString qname = QT_UTF8(name);
		QAction *popupItem = new QAction(qname, this);
J
jp9000 已提交
4666
		popupItem->setData(QT_UTF8(type));
J
jp9000 已提交
4667 4668
		connect(popupItem, SIGNAL(triggered(bool)), this,
			SLOT(AddSourceFromAction()));
J
jp9000 已提交
4669

C
Clayton Groeneveld 已提交
4670 4671 4672 4673 4674 4675 4676 4677 4678
		QIcon icon;

		if (strcmp(type, "scene") == 0)
			icon = GetSceneIcon();
		else
			icon = GetSourceIcon(type);

		popupItem->setIcon(icon);

J
jp9000 已提交
4679 4680
		QAction *after = getActionAfter(popup, qname);
		popup->insertAction(after, popupItem);
J
jp9000 已提交
4681
	};
4682

J
jp9000 已提交
4683 4684
	while (obs_enum_input_types(idx++, &type)) {
		const char *name = obs_source_get_display_name(type);
4685
		uint32_t caps = obs_get_source_output_flags(type);
J
jp9000 已提交
4686

4687 4688 4689
		if ((caps & OBS_SOURCE_CAP_DISABLED) != 0)
			continue;

4690 4691
		if ((caps & OBS_SOURCE_DEPRECATED) == 0) {
			addSource(popup, type, name);
4692 4693 4694
		} else {
			addSource(deprecated, type, name);
			foundDeprecated = true;
4695
		}
4696
		foundValues = true;
4697 4698
	}

J
jp9000 已提交
4699
	addSource(popup, "scene", Str("Basic.Scene"));
J
jp9000 已提交
4700

J
jp9000 已提交
4701 4702
	popup->addSeparator();
	QAction *addGroup = new QAction(QTStr("Group"), this);
4703
	addGroup->setData(QT_UTF8("group"));
C
Clayton Groeneveld 已提交
4704
	addGroup->setIcon(GetGroupIcon());
J
jp9000 已提交
4705 4706
	connect(addGroup, SIGNAL(triggered(bool)), this,
		SLOT(AddSourceFromAction()));
J
jp9000 已提交
4707 4708
	popup->addAction(addGroup);

4709 4710 4711 4712 4713
	if (!foundDeprecated) {
		delete deprecated;
		deprecated = nullptr;
	}

4714 4715 4716
	if (!foundValues) {
		delete popup;
		popup = nullptr;
4717 4718

	} else if (foundDeprecated) {
J
jp9000 已提交
4719
		popup->addSeparator();
4720
		popup->addMenu(deprecated);
4721
	}
4722 4723 4724 4725 4726 4727

	return popup;
}

void OBSBasic::AddSourceFromAction()
{
J
jp9000 已提交
4728
	QAction *action = qobject_cast<QAction *>(sender());
4729 4730 4731 4732 4733 4734 4735 4736 4737 4738
	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 已提交
4739 4740 4741
		OBSMessageBox::information(
			this, QTStr("Basic.Main.AddSourceHelp.Title"),
			QTStr("Basic.Main.AddSourceHelp.Text"));
4742 4743 4744
		return;
	}

4745
	QScopedPointer<QMenu> popup(CreateAddSourcePopupMenu());
4746 4747
	if (popup)
		popup->exec(pos);
4748 4749
}

J
jp9000 已提交
4750
void OBSBasic::on_actionAddSource_triggered()
4751
{
J
jp9000 已提交
4752
	AddSourcePopupMenu(QCursor::pos());
4753 4754
}

J
jp9000 已提交
4755 4756 4757
static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param)
{
	vector<OBSSceneItem> &items =
J
jp9000 已提交
4758
		*reinterpret_cast<vector<OBSSceneItem> *>(param);
J
jp9000 已提交
4759 4760 4761 4762 4763 4764 4765 4766 4767

	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 已提交
4768
void OBSBasic::on_actionRemoveSource_triggered()
4769
{
4770
	vector<OBSSceneItem> items;
4771

J
jp9000 已提交
4772
	obs_scene_enum_items(GetCurrentScene(), remove_items, &items);
4773 4774 4775 4776

	if (!items.size())
		return;

J
jp9000 已提交
4777
	auto removeMultiple = [this](size_t count) {
4778
		QString text = QTStr("ConfirmRemove.TextMultiple")
J
jp9000 已提交
4779
				       .arg(QString::number(count));
4780 4781 4782

		QMessageBox remove_items(this);
		remove_items.setText(text);
J
jp9000 已提交
4783 4784
		QAbstractButton *Yes = remove_items.addButton(
			QTStr("Yes"), QMessageBox::YesRole);
4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804
		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);
		}
	}
4805 4806
}

J
John Bradley 已提交
4807 4808 4809 4810 4811 4812 4813 4814 4815
void OBSBasic::on_actionInteract_triggered()
{
	OBSSceneItem item = GetCurrentSceneItem();
	OBSSource source = obs_sceneitem_get_source(item);

	if (source)
		CreateInteractionWindow(source);
}

J
jp9000 已提交
4816
void OBSBasic::on_actionSourceProperties_triggered()
4817
{
4818
	OBSSceneItem item = GetCurrentSceneItem();
J
jp9000 已提交
4819
	OBSSource source = obs_sceneitem_get_source(item);
4820

4821 4822
	if (source)
		CreatePropertiesWindow(source);
4823 4824
}

J
jp9000 已提交
4825
void OBSBasic::on_actionSourceUp_triggered()
4826
{
J
jp9000 已提交
4827
	OBSSceneItem item = GetCurrentSceneItem();
J
jp9000 已提交
4828
	obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
4829
}
J
jp9000 已提交
4830

J
jp9000 已提交
4831
void OBSBasic::on_actionSourceDown_triggered()
4832
{
J
jp9000 已提交
4833
	OBSSceneItem item = GetCurrentSceneItem();
J
jp9000 已提交
4834
	obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
4835 4836
}

J
jp9000 已提交
4837 4838 4839
void OBSBasic::on_actionMoveUp_triggered()
{
	OBSSceneItem item = GetCurrentSceneItem();
J
jp9000 已提交
4840
	obs_sceneitem_set_order(item, OBS_ORDER_MOVE_UP);
J
jp9000 已提交
4841 4842 4843 4844 4845
}

void OBSBasic::on_actionMoveDown_triggered()
{
	OBSSceneItem item = GetCurrentSceneItem();
J
jp9000 已提交
4846
	obs_sceneitem_set_order(item, OBS_ORDER_MOVE_DOWN);
J
jp9000 已提交
4847 4848 4849 4850 4851
}

void OBSBasic::on_actionMoveToTop_triggered()
{
	OBSSceneItem item = GetCurrentSceneItem();
J
jp9000 已提交
4852
	obs_sceneitem_set_order(item, OBS_ORDER_MOVE_TOP);
J
jp9000 已提交
4853 4854 4855 4856 4857
}

void OBSBasic::on_actionMoveToBottom_triggered()
{
	OBSSceneItem item = GetCurrentSceneItem();
J
jp9000 已提交
4858
	obs_sceneitem_set_order(item, OBS_ORDER_MOVE_BOTTOM);
J
jp9000 已提交
4859 4860
}

4861
static BPtr<char> ReadLogFile(const char *subdir, const char *log)
J
jp9000 已提交
4862
{
4863
	char logDir[512];
4864
	if (GetConfigPath(logDir, sizeof(logDir), subdir) <= 0)
4865
		return nullptr;
J
jp9000 已提交
4866

J
jpark37 已提交
4867
	string path = logDir;
J
jp9000 已提交
4868 4869 4870
	path += "/";
	path += log;

4871
	BPtr<char> file = os_quick_read_utf8_file(path.c_str());
J
jp9000 已提交
4872 4873 4874 4875 4876 4877
	if (!file)
		blog(LOG_WARNING, "Failed to read log file %s", path.c_str());

	return file;
}

4878
void OBSBasic::UploadLog(const char *subdir, const char *file)
J
jp9000 已提交
4879
{
4880
	BPtr<char> fileString{ReadLogFile(subdir, file)};
J
jp9000 已提交
4881

4882
	if (!fileString)
J
jp9000 已提交
4883 4884
		return;

4885
	if (!*fileString)
J
jp9000 已提交
4886 4887 4888 4889
		return;

	ui->menuLogFiles->setEnabled(false);

4890
	stringstream ss;
J
jp9000 已提交
4891 4892 4893
	ss << "OBS " << App()->GetVersionString() << " log file uploaded at "
	   << CurrentDateTimeString() << "\n\n"
	   << fileString;
F
fryshorts 已提交
4894

4895 4896 4897
	if (logUploadThread) {
		logUploadThread->wait();
	}
F
fryshorts 已提交
4898

J
jp9000 已提交
4899 4900 4901
	RemoteTextThread *thread =
		new RemoteTextThread("https://obsproject.com/logs/upload",
				     "text/plain", ss.str().c_str());
4902

4903
	logUploadThread.reset(thread);
J
jp9000 已提交
4904 4905
	connect(thread, &RemoteTextThread::Result, this,
		&OBSBasic::logUploadFinished);
4906
	logUploadThread->start();
J
jp9000 已提交
4907 4908
}

P
Palana 已提交
4909 4910
void OBSBasic::on_actionShowLogs_triggered()
{
4911
	char logDir[512];
4912
	if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
4913 4914
		return;

P
Palana 已提交
4915 4916 4917 4918
	QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir));
	QDesktopServices::openUrl(url);
}

J
jp9000 已提交
4919 4920
void OBSBasic::on_actionUploadCurrentLog_triggered()
{
4921
	UploadLog("obs-studio/logs", App()->GetCurrentLog());
J
jp9000 已提交
4922 4923 4924 4925
}

void OBSBasic::on_actionUploadLastLog_triggered()
{
4926
	UploadLog("obs-studio/logs", App()->GetLastLog());
J
jp9000 已提交
4927 4928
}

4929 4930 4931
void OBSBasic::on_actionViewCurrentLog_triggered()
{
	char logDir[512];
4932
	if (GetConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0)
4933 4934
		return;

J
jp9000 已提交
4935
	const char *log = App()->GetCurrentLog();
4936

J
jpark37 已提交
4937
	string path = logDir;
4938 4939 4940 4941 4942 4943 4944
	path += "/";
	path += log;

	QUrl url = QUrl::fromLocalFile(QT_UTF8(path.c_str()));
	QDesktopServices::openUrl(url);
}

J
jp9000 已提交
4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959
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 已提交
4960 4961
void OBSBasic::on_actionCheckForUpdates_triggered()
{
J
jp9000 已提交
4962
	CheckForUpdates(true);
J
jp9000 已提交
4963 4964
}

4965
void OBSBasic::logUploadFinished(const QString &text, const QString &error)
J
jp9000 已提交
4966 4967 4968
{
	ui->menuLogFiles->setEnabled(true);

4969
	if (text.isEmpty()) {
J
jp9000 已提交
4970 4971 4972
		OBSMessageBox::critical(
			this, QTStr("LogReturnDialog.ErrorUploadingLog"),
			error);
J
jp9000 已提交
4973 4974 4975
		return;
	}

4976
	obs_data_t *returnData = obs_data_create_from_json(QT_TO_UTF8(text));
4977
	string resURL = obs_data_get_string(returnData, "url");
4978
	QString logURL = resURL.c_str();
J
jp9000 已提交
4979 4980 4981 4982 4983 4984
	obs_data_release(returnData);

	OBSLogReply logDialog(this, logURL);
	logDialog.exec();
}

J
jp9000 已提交
4985
static void RenameListItem(OBSBasic *parent, QListWidget *listWidget,
J
jp9000 已提交
4986
			   obs_source_t *source, const string &name)
4987
{
4988 4989 4990 4991
	const char *prevName = obs_source_get_name(source);
	if (name == prevName)
		return;

J
jp9000 已提交
4992 4993
	obs_source_t *foundSource = obs_get_source_by_name(name.c_str());
	QListWidgetItem *listItem = listWidget->currentItem();
4994

4995
	if (foundSource || name.empty()) {
4996
		listItem->setText(QT_UTF8(prevName));
4997

4998
		if (foundSource) {
4999
			OBSMessageBox::warning(parent,
J
jp9000 已提交
5000 5001
					       QTStr("NameExists.Title"),
					       QTStr("NameExists.Text"));
5002
		} else if (name.empty()) {
5003
			OBSMessageBox::warning(parent,
J
jp9000 已提交
5004 5005
					       QTStr("NoNameEntered.Title"),
					       QTStr("NoNameEntered.Text"));
5006 5007
		}

5008 5009 5010
		obs_source_release(foundSource);
	} else {
		listItem->setText(QT_UTF8(name.c_str()));
5011
		obs_source_set_name(source, name.c_str());
5012 5013 5014
	}
}

J
jp9000 已提交
5015
void OBSBasic::SceneNameEdited(QWidget *editor,
J
jp9000 已提交
5016
			       QAbstractItemDelegate::EndEditHint endHint)
J
jp9000 已提交
5017
{
J
jp9000 已提交
5018 5019 5020
	OBSScene scene = GetCurrentScene();
	QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
	string text = QT_TO_UTF8(edit->text().trimmed());
J
jp9000 已提交
5021 5022 5023 5024

	if (!scene)
		return;

5025
	obs_source_t *source = obs_scene_get_source(scene);
5026
	RenameListItem(this, ui->scenes, source, text);
J
jp9000 已提交
5027

J
jp9000 已提交
5028 5029 5030
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED);

J
jp9000 已提交
5031 5032 5033
	UNUSED_PARAMETER(endHint);
}

J
jp9000 已提交
5034 5035 5036 5037 5038 5039 5040 5041
void OBSBasic::OpenFilters()
{
	OBSSceneItem item = GetCurrentSceneItem();
	OBSSource source = obs_sceneitem_get_source(item);

	CreateFiltersWindow(source);
}

J
jp9000 已提交
5042 5043 5044 5045 5046 5047 5048 5049
void OBSBasic::OpenSceneFilters()
{
	OBSScene scene = GetCurrentScene();
	OBSSource source = obs_scene_get_source(scene);

	CreateFiltersWindow(source);
}

J
jp9000 已提交
5050 5051 5052 5053
#define RECORDING_START \
	"==== Recording Start ==============================================="
#define RECORDING_STOP \
	"==== Recording Stop ================================================"
J
jp9000 已提交
5054 5055 5056 5057
#define REPLAY_BUFFER_START \
	"==== Replay Buffer Start ==========================================="
#define REPLAY_BUFFER_STOP \
	"==== Replay Buffer Stop ============================================"
J
jp9000 已提交
5058 5059 5060 5061 5062
#define STREAMING_START \
	"==== Streaming Start ==============================================="
#define STREAMING_STOP \
	"==== Streaming Stop ================================================"

5063 5064
void OBSBasic::StartStreaming()
{
J
jp9000 已提交
5065 5066
	if (outputHandler->StreamingActive())
		return;
5067
	if (disableOutputsRef)
5068
		return;
J
jp9000 已提交
5069 5070 5071 5072

	if (api)
		api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTING);

5073 5074
	SaveProject();

J
jp9000 已提交
5075 5076
	ui->streamButton->setEnabled(false);
	ui->streamButton->setText(QTStr("Basic.Main.Connecting"));
5077 5078 5079 5080 5081

	if (sysTrayStream) {
		sysTrayStream->setEnabled(false);
		sysTrayStream->setText(ui->streamButton->text());
	}
5082

J
jp9000 已提交
5083
	if (!outputHandler->StartStreaming(service)) {
J
jp9000 已提交
5084 5085 5086 5087
		QString message =
			!outputHandler->lastError.empty()
				? QTStr(outputHandler->lastError.c_str())
				: QTStr("Output.StartFailedGeneric");
J
jp9000 已提交
5088 5089
		ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
		ui->streamButton->setEnabled(true);
5090
		ui->streamButton->setChecked(false);
5091 5092 5093 5094 5095

		if (sysTrayStream) {
			sysTrayStream->setText(ui->streamButton->text());
			sysTrayStream->setEnabled(true);
		}
5096

5097
		QMessageBox::critical(this, QTStr("Output.StartStreamFailed"),
J
jp9000 已提交
5098
				      message);
5099
		return;
5100
	}
5101

J
jp9000 已提交
5102 5103
	bool recordWhenStreaming = config_get_bool(
		GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
5104 5105
	if (recordWhenStreaming)
		StartRecording();
5106

J
jp9000 已提交
5107 5108
	bool replayBufferWhileStreaming = config_get_bool(
		GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
5109 5110
	if (replayBufferWhileStreaming)
		StartReplayBuffer();
5111 5112
}

5113 5114 5115 5116
#ifdef _WIN32
static inline void UpdateProcessPriority()
{
	const char *priority = config_get_string(App()->GlobalConfig(),
J
jp9000 已提交
5117
						 "General", "ProcessPriority");
5118 5119 5120 5121 5122 5123 5124
	if (priority && strcmp(priority, "Normal") != 0)
		SetProcessPriority(priority);
}

static inline void ClearProcessPriority()
{
	const char *priority = config_get_string(App()->GlobalConfig(),
J
jp9000 已提交
5125
						 "General", "ProcessPriority");
5126 5127 5128 5129
	if (priority && strcmp(priority, "Normal") != 0)
		SetProcessPriority("Normal");
}
#else
J
jp9000 已提交
5130 5131 5132 5133 5134 5135
#define UpdateProcessPriority() \
	do {                    \
	} while (false)
#define ClearProcessPriority() \
	do {                   \
	} while (false)
5136 5137
#endif

5138
inline void OBSBasic::OnActivate()
5139
{
5140 5141
	if (ui->profileMenu->isEnabled()) {
		ui->profileMenu->setEnabled(false);
J
jp9000 已提交
5142
		ui->autoConfigure->setEnabled(false);
5143 5144
		App()->IncrementSleepInhibition();
		UpdateProcessPriority();
C
cg2121 已提交
5145

5146
		if (trayIcon)
J
jp9000 已提交
5147 5148 5149
			trayIcon->setIcon(QIcon::fromTheme(
				"obs-tray-active",
				QIcon(":/res/images/tray_active.png")));
5150 5151
	}
}
J
jp9000 已提交
5152

5153 5154 5155
extern volatile bool recording_paused;
extern volatile bool replaybuf_active;

5156 5157
inline void OBSBasic::OnDeactivate()
{
5158
	if (!outputHandler->Active() && !ui->profileMenu->isEnabled()) {
J
jp9000 已提交
5159
		ui->profileMenu->setEnabled(true);
J
jp9000 已提交
5160
		ui->autoConfigure->setEnabled(true);
5161
		App()->DecrementSleepInhibition();
5162
		ClearProcessPriority();
C
cg2121 已提交
5163

5164
		if (trayIcon)
J
jp9000 已提交
5165 5166
			trayIcon->setIcon(QIcon::fromTheme(
				"obs-tray", QIcon(":/res/images/obs.png")));
5167 5168 5169 5170
	} else if (trayIcon) {
		if (os_atomic_load_bool(&recording_paused))
			trayIcon->setIcon(QIcon(":/res/images/obs_paused.png"));
		else
5171 5172
			trayIcon->setIcon(
				QIcon(":/res/images/tray_active.png"));
J
jp9000 已提交
5173
	}
5174 5175 5176 5177 5178 5179 5180
}

void OBSBasic::StopStreaming()
{
	SaveProject();

	if (outputHandler->StreamingActive())
5181
		outputHandler->StopStreaming(streamingStopping);
5182 5183

	OnDeactivate();
5184

J
jp9000 已提交
5185 5186 5187 5188 5189
	bool recordWhenStreaming = config_get_bool(
		GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
	bool keepRecordingWhenStreamStops =
		config_get_bool(GetGlobalConfig(), "BasicWindow",
				"KeepRecordingWhenStreamStops");
5190 5191
	if (recordWhenStreaming && !keepRecordingWhenStreamStops)
		StopRecording();
5192

J
jp9000 已提交
5193 5194 5195 5196 5197
	bool replayBufferWhileStreaming = config_get_bool(
		GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
	bool keepReplayBufferStreamStops =
		config_get_bool(GetGlobalConfig(), "BasicWindow",
				"KeepReplayBufferStreamStops");
5198 5199
	if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
		StopReplayBuffer();
5200 5201
}

J
jp9000 已提交
5202 5203 5204 5205 5206
void OBSBasic::ForceStopStreaming()
{
	SaveProject();

	if (outputHandler->StreamingActive())
5207
		outputHandler->StopStreaming(true);
J
jp9000 已提交
5208

5209
	OnDeactivate();
5210

J
jp9000 已提交
5211 5212 5213 5214 5215
	bool recordWhenStreaming = config_get_bool(
		GetGlobalConfig(), "BasicWindow", "RecordWhenStreaming");
	bool keepRecordingWhenStreamStops =
		config_get_bool(GetGlobalConfig(), "BasicWindow",
				"KeepRecordingWhenStreamStops");
5216 5217
	if (recordWhenStreaming && !keepRecordingWhenStreamStops)
		StopRecording();
5218

J
jp9000 已提交
5219 5220 5221 5222 5223
	bool replayBufferWhileStreaming = config_get_bool(
		GetGlobalConfig(), "BasicWindow", "ReplayBufferWhileStreaming");
	bool keepReplayBufferStreamStops =
		config_get_bool(GetGlobalConfig(), "BasicWindow",
				"KeepReplayBufferStreamStops");
5224 5225
	if (replayBufferWhileStreaming && !keepReplayBufferStreamStops)
		StopReplayBuffer();
J
jp9000 已提交
5226 5227 5228 5229 5230 5231
}

void OBSBasic::StreamDelayStarting(int sec)
{
	ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
	ui->streamButton->setEnabled(true);
5232
	ui->streamButton->setChecked(true);
5233 5234 5235 5236 5237

	if (sysTrayStream) {
		sysTrayStream->setText(ui->streamButton->text());
		sysTrayStream->setEnabled(true);
	}
J
jp9000 已提交
5238 5239 5240 5241 5242

	if (!startStreamMenu.isNull())
		startStreamMenu->deleteLater();

	startStreamMenu = new QMenu();
J
jp9000 已提交
5243 5244 5245 5246
	startStreamMenu->addAction(QTStr("Basic.Main.StopStreaming"), this,
				   SLOT(StopStreaming()));
	startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
				   SLOT(ForceStopStreaming()));
J
jp9000 已提交
5247 5248 5249
	ui->streamButton->setMenu(startStreamMenu);

	ui->statusbar->StreamDelayStarting(sec);
5250

5251
	OnActivate();
J
jp9000 已提交
5252 5253 5254 5255 5256 5257
}

void OBSBasic::StreamDelayStopping(int sec)
{
	ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
	ui->streamButton->setEnabled(true);
5258
	ui->streamButton->setChecked(false);
5259 5260 5261 5262 5263

	if (sysTrayStream) {
		sysTrayStream->setText(ui->streamButton->text());
		sysTrayStream->setEnabled(true);
	}
J
jp9000 已提交
5264 5265 5266 5267 5268

	if (!startStreamMenu.isNull())
		startStreamMenu->deleteLater();

	startStreamMenu = new QMenu();
J
jp9000 已提交
5269 5270 5271 5272
	startStreamMenu->addAction(QTStr("Basic.Main.StartStreaming"), this,
				   SLOT(StartStreaming()));
	startStreamMenu->addAction(QTStr("Basic.Main.ForceStopStreaming"), this,
				   SLOT(ForceStopStreaming()));
J
jp9000 已提交
5273 5274 5275
	ui->streamButton->setMenu(startStreamMenu);

	ui->statusbar->StreamDelayStopping(sec);
5276 5277 5278

	if (api)
		api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
J
jp9000 已提交
5279 5280
}

5281
void OBSBasic::StreamingStart()
5282
{
5283
	ui->streamButton->setText(QTStr("Basic.Main.StopStreaming"));
J
jp9000 已提交
5284
	ui->streamButton->setEnabled(true);
5285
	ui->streamButton->setChecked(true);
J
jp9000 已提交
5286
	ui->statusbar->StreamStarted(outputHandler->streamOutput);
5287 5288 5289 5290 5291

	if (sysTrayStream) {
		sysTrayStream->setText(ui->streamButton->text());
		sysTrayStream->setEnabled(true);
	}
5292

J
jp9000 已提交
5293 5294 5295
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_STREAMING_STARTED);

5296
	OnActivate();
5297

5298
	blog(LOG_INFO, STREAMING_START);
5299 5300
}

5301 5302 5303
void OBSBasic::StreamStopping()
{
	ui->streamButton->setText(QTStr("Basic.Main.StoppingStreaming"));
5304 5305 5306

	if (sysTrayStream)
		sysTrayStream->setText(ui->streamButton->text());
J
jp9000 已提交
5307

5308
	streamingStopping = true;
J
jp9000 已提交
5309 5310
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPING);
5311 5312
}

5313
void OBSBasic::StreamingStop(int code, QString last_error)
5314
{
5315
	const char *errorDescription = "";
5316 5317
	DStr errorMessage;
	bool use_last_error = false;
5318
	bool encode_error = false;
5319 5320 5321

	switch (code) {
	case OBS_OUTPUT_BAD_PATH:
5322
		errorDescription = Str("Output.ConnectFail.BadPath");
5323 5324 5325
		break;

	case OBS_OUTPUT_CONNECT_FAILED:
5326 5327
		use_last_error = true;
		errorDescription = Str("Output.ConnectFail.ConnectFailed");
5328 5329 5330
		break;

	case OBS_OUTPUT_INVALID_STREAM:
5331
		errorDescription = Str("Output.ConnectFail.InvalidStream");
5332 5333
		break;

5334 5335 5336 5337
	case OBS_OUTPUT_ENCODE_ERROR:
		encode_error = true;
		break;

5338
	default:
5339
	case OBS_OUTPUT_ERROR:
5340 5341
		use_last_error = true;
		errorDescription = Str("Output.ConnectFail.Error");
5342 5343 5344 5345 5346
		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 */
5347 5348
		use_last_error = true;
		errorDescription = Str("Output.ConnectFail.Disconnected");
5349 5350
	}

5351 5352
	if (use_last_error && !last_error.isEmpty())
		dstr_printf(errorMessage, "%s\n\n%s", errorDescription,
J
jp9000 已提交
5353
			    QT_TO_UTF8(last_error));
5354 5355 5356
	else
		dstr_copy(errorMessage, errorDescription);

J
jp9000 已提交
5357
	ui->statusbar->StreamStopped();
5358

5359
	ui->streamButton->setText(QTStr("Basic.Main.StartStreaming"));
J
jp9000 已提交
5360
	ui->streamButton->setEnabled(true);
5361
	ui->streamButton->setChecked(false);
5362 5363 5364 5365 5366

	if (sysTrayStream) {
		sysTrayStream->setText(ui->streamButton->text());
		sysTrayStream->setEnabled(true);
	}
5367

5368
	streamingStopping = false;
J
jp9000 已提交
5369 5370 5371
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_STREAMING_STOPPED);

5372
	OnDeactivate();
5373 5374

	blog(LOG_INFO, STREAMING_STOP);
J
jp9000 已提交
5375

5376
	if (encode_error) {
J
jp9000 已提交
5377 5378 5379
		OBSMessageBox::information(
			this, QTStr("Output.StreamEncodeError.Title"),
			QTStr("Output.StreamEncodeError.Msg"));
5380 5381

	} else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
5382
		OBSMessageBox::information(this,
J
jp9000 已提交
5383 5384
					   QTStr("Output.ConnectFail.Title"),
					   QT_UTF8(errorMessage));
5385

C
cg2121 已提交
5386
	} else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
J
jp9000 已提交
5387 5388
		SysTrayNotify(QT_UTF8(errorDescription),
			      QSystemTrayIcon::Warning);
C
cg2121 已提交
5389
	}
J
jp9000 已提交
5390 5391 5392 5393 5394 5395

	if (!startStreamMenu.isNull()) {
		ui->streamButton->setMenu(nullptr);
		startStreamMenu->deleteLater();
		startStreamMenu = nullptr;
	}
J
jp9000 已提交
5396 5397
}

C
cg2121 已提交
5398 5399 5400
void OBSBasic::AutoRemux()
{
	const char *mode = config_get_string(basicConfig, "Output", "Mode");
5401 5402
	bool advanced = astrcmpi(mode, "Advanced") == 0;

J
jp9000 已提交
5403 5404 5405 5406 5407
	const char *path = !advanced ? config_get_string(basicConfig,
							 "SimpleOutput",
							 "FilePath")
				     : config_get_string(basicConfig, "AdvOut",
							 "RecFilePath");
5408

5409 5410
	/* do not save if using FFmpeg output in advanced output mode */
	if (advanced) {
J
jp9000 已提交
5411 5412
		const char *type =
			config_get_string(basicConfig, "AdvOut", "RecType");
5413 5414 5415 5416 5417
		if (astrcmpi(type, "FFmpeg") == 0) {
			return;
		}
	}

J
jp9000 已提交
5418 5419 5420 5421 5422 5423 5424
	QString input;
	input += path;
	input += "/";
	input += remuxFilename.c_str();

	QFileInfo fi(remuxFilename.c_str());

5425 5426 5427 5428 5429
	/* do not remux if lossless */
	if (fi.suffix().compare("avi", Qt::CaseInsensitive) == 0) {
		return;
	}

J
jp9000 已提交
5430 5431 5432 5433 5434
	QString output;
	output += path;
	output += "/";
	output += fi.completeBaseName();
	output += ".mp4";
C
cg2121 已提交
5435 5436 5437

	OBSRemux *remux = new OBSRemux(path, this, true);
	remux->show();
J
jp9000 已提交
5438
	remux->AutoRemux(input, output);
C
cg2121 已提交
5439 5440
}

5441 5442
void OBSBasic::StartRecording()
{
5443 5444
	if (outputHandler->RecordingActive())
		return;
5445
	if (disableOutputsRef)
5446
		return;
5447

5448 5449 5450 5451 5452 5453
	if (!OutputPathValid()) {
		OutputPathInvalidMessage();
		ui->recordButton->setChecked(false);
		return;
	}

5454 5455 5456 5457 5458 5459
	if (LowDiskSpace()) {
		DiskSpaceMessage();
		ui->recordButton->setChecked(false);
		return;
	}

J
jp9000 已提交
5460 5461 5462
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTING);

5463
	SaveProject();
5464 5465 5466

	if (!outputHandler->StartRecording())
		ui->recordButton->setChecked(false);
5467 5468
}

5469 5470
void OBSBasic::RecordStopping()
{
J
jp9000 已提交
5471
	ui->recordButton->setText(QTStr("Basic.Main.StoppingRecording"));
5472 5473 5474

	if (sysTrayRecord)
		sysTrayRecord->setText(ui->recordButton->text());
J
jp9000 已提交
5475

5476
	recordingStopping = true;
J
jp9000 已提交
5477 5478
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPING);
5479 5480
}

5481 5482 5483 5484 5485
void OBSBasic::StopRecording()
{
	SaveProject();

	if (outputHandler->RecordingActive())
5486
		outputHandler->StopRecording(recordingStopping);
J
jp9000 已提交
5487

5488
	OnDeactivate();
5489 5490
}

P
Palana 已提交
5491 5492
void OBSBasic::RecordingStart()
{
J
jp9000 已提交
5493
	ui->statusbar->RecordingStarted(outputHandler->fileOutput);
J
jp9000 已提交
5494
	ui->recordButton->setText(QTStr("Basic.Main.StopRecording"));
5495
	ui->recordButton->setChecked(true);
5496 5497 5498

	if (sysTrayRecord)
		sysTrayRecord->setText(ui->recordButton->text());
5499

5500
	recordingStopping = false;
J
jp9000 已提交
5501 5502 5503
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_RECORDING_STARTED);

5504 5505 5506
	if (!diskFullTimer->isActive())
		diskFullTimer->start(1000);

5507
	OnActivate();
J
jp9000 已提交
5508
	UpdatePause();
5509

5510
	blog(LOG_INFO, RECORDING_START);
P
Palana 已提交
5511 5512
}

5513
void OBSBasic::RecordingStop(int code, QString last_error)
5514
{
P
Palana 已提交
5515
	ui->statusbar->RecordingStopped();
J
jp9000 已提交
5516
	ui->recordButton->setText(QTStr("Basic.Main.StartRecording"));
5517
	ui->recordButton->setChecked(false);
5518 5519 5520

	if (sysTrayRecord)
		sysTrayRecord->setText(ui->recordButton->text());
J
jp9000 已提交
5521

5522
	blog(LOG_INFO, RECORDING_STOP);
5523

C
cg2121 已提交
5524
	if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
J
jp9000 已提交
5525 5526
		OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
					QTStr("Output.RecordFail.Unsupported"));
J
jp9000 已提交
5527

5528
	} else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) {
J
jp9000 已提交
5529 5530 5531
		OBSMessageBox::warning(
			this, QTStr("Output.RecordError.Title"),
			QTStr("Output.RecordError.EncodeErrorMsg"));
5532

C
cg2121 已提交
5533
	} else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
5534
		OBSMessageBox::warning(this,
J
jp9000 已提交
5535 5536
				       QTStr("Output.RecordNoSpace.Title"),
				       QTStr("Output.RecordNoSpace.Msg"));
J
jp9000 已提交
5537

C
cg2121 已提交
5538
	} else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
5539 5540 5541 5542 5543 5544 5545 5546 5547

		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 已提交
5548
				    QT_TO_UTF8(last_error));
5549 5550 5551
		else
			dstr_copy(errorMessage, errorDescription);

J
jp9000 已提交
5552 5553
		OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
					QT_UTF8(errorMessage));
C
cg2121 已提交
5554 5555 5556

	} else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
		SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
J
jp9000 已提交
5557
			      QSystemTrayIcon::Warning);
C
cg2121 已提交
5558 5559 5560

	} else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
		SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
J
jp9000 已提交
5561
			      QSystemTrayIcon::Warning);
C
cg2121 已提交
5562 5563 5564

	} else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
		SysTrayNotify(QTStr("Output.RecordError.Msg"),
J
jp9000 已提交
5565
			      QSystemTrayIcon::Warning);
J
jp9000 已提交
5566 5567
	}

J
jp9000 已提交
5568 5569 5570
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_RECORDING_STOPPED);

5571 5572 5573
	if (diskFullTimer->isActive())
		diskFullTimer->stop();

C
cg2121 已提交
5574 5575 5576
	if (remuxAfterRecord)
		AutoRemux();

5577
	OnDeactivate();
J
jp9000 已提交
5578
	UpdatePause(false);
5579
}
5580

J
jp9000 已提交
5581
#define RP_NO_HOTKEY_TITLE QTStr("Output.ReplayBuffer.NoHotkey.Title")
J
jp9000 已提交
5582
#define RP_NO_HOTKEY_TEXT QTStr("Output.ReplayBuffer.NoHotkey.Msg")
J
jp9000 已提交
5583

J
jp9000 已提交
5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614
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 已提交
5615 5616 5617 5618 5619 5620
void OBSBasic::StartReplayBuffer()
{
	if (!outputHandler || !outputHandler->replayBuffer)
		return;
	if (outputHandler->ReplayBufferActive())
		return;
5621
	if (disableOutputsRef)
5622
		return;
J
jp9000 已提交
5623

J
JohannMG 已提交
5624
	if (!UIValidation::NoSourcesConfirmation(this)) {
5625 5626 5627 5628
		replayBufferButton->setChecked(false);
		return;
	}

5629 5630 5631 5632 5633 5634
	if (LowDiskSpace()) {
		DiskSpaceMessage();
		replayBufferButton->setChecked(false);
		return;
	}

J
jp9000 已提交
5635 5636
	obs_output_t *output = outputHandler->replayBuffer;
	obs_data_t *hotkeys = obs_hotkeys_save_output(output);
J
jp9000 已提交
5637 5638
	obs_data_array_t *bindings =
		obs_data_get_array(hotkeys, "ReplayBuffer.Save");
J
jp9000 已提交
5639 5640 5641 5642 5643
	size_t count = obs_data_array_count(bindings);
	obs_data_array_release(bindings);
	obs_data_release(hotkeys);

	if (!count) {
J
jp9000 已提交
5644 5645
		OBSMessageBox::information(this, RP_NO_HOTKEY_TITLE,
					   RP_NO_HOTKEY_TEXT);
5646
		replayBufferButton->setChecked(false);
J
jp9000 已提交
5647 5648 5649 5650 5651 5652 5653
		return;
	}

	if (api)
		api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTING);

	SaveProject();
J
jp9000 已提交
5654 5655

	if (!outputHandler->StartReplayBuffer()) {
5656
		replayBufferButton->setChecked(false);
J
jp9000 已提交
5657 5658 5659
	} else if (os_atomic_load_bool(&recording_paused)) {
		ShowReplayBufferPauseWarning();
	}
J
jp9000 已提交
5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695
}

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"));
5696
	replayBufferButton->setChecked(true);
J
jp9000 已提交
5697 5698 5699 5700 5701 5702 5703 5704 5705

	if (sysTrayReplayBuffer)
		sysTrayReplayBuffer->setText(replayBufferButton->text());

	replayBufferStopping = false;
	if (api)
		api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED);

	OnActivate();
5706
	UpdateReplayBuffer();
J
jp9000 已提交
5707 5708 5709 5710

	blog(LOG_INFO, REPLAY_BUFFER_START);
}

5711 5712 5713 5714 5715 5716 5717 5718
void OBSBasic::ReplayBufferSave()
{
	if (!outputHandler || !outputHandler->replayBuffer)
		return;
	if (!outputHandler->ReplayBufferActive())
		return;

	calldata_t cd = {0};
J
jp9000 已提交
5719 5720
	proc_handler_t *ph =
		obs_output_get_proc_handler(outputHandler->replayBuffer);
5721 5722 5723 5724
	proc_handler_call(ph, "save", &cd);
	calldata_free(&cd);
}

J
jp9000 已提交
5725 5726 5727 5728 5729 5730
void OBSBasic::ReplayBufferStop(int code)
{
	if (!outputHandler || !outputHandler->replayBuffer)
		return;

	replayBufferButton->setText(QTStr("Basic.Main.StartReplayBuffer"));
5731
	replayBufferButton->setChecked(false);
J
jp9000 已提交
5732 5733 5734 5735 5736 5737 5738

	if (sysTrayReplayBuffer)
		sysTrayReplayBuffer->setText(replayBufferButton->text());

	blog(LOG_INFO, REPLAY_BUFFER_STOP);

	if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) {
J
jp9000 已提交
5739 5740
		OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"),
					QTStr("Output.RecordFail.Unsupported"));
J
jp9000 已提交
5741 5742

	} else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) {
5743
		OBSMessageBox::warning(this,
J
jp9000 已提交
5744 5745
				       QTStr("Output.RecordNoSpace.Title"),
				       QTStr("Output.RecordNoSpace.Msg"));
J
jp9000 已提交
5746 5747

	} else if (code != OBS_OUTPUT_SUCCESS && isVisible()) {
J
jp9000 已提交
5748 5749
		OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"),
					QTStr("Output.RecordError.Msg"));
J
jp9000 已提交
5750 5751 5752

	} else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) {
		SysTrayNotify(QTStr("Output.RecordFail.Unsupported"),
J
jp9000 已提交
5753
			      QSystemTrayIcon::Warning);
J
jp9000 已提交
5754 5755 5756

	} else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) {
		SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"),
J
jp9000 已提交
5757
			      QSystemTrayIcon::Warning);
J
jp9000 已提交
5758 5759 5760

	} else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) {
		SysTrayNotify(QTStr("Output.RecordError.Msg"),
J
jp9000 已提交
5761
			      QSystemTrayIcon::Warning);
J
jp9000 已提交
5762 5763 5764 5765 5766 5767
	}

	if (api)
		api->on_event(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED);

	OnDeactivate();
5768
	UpdateReplayBuffer(false);
J
jp9000 已提交
5769 5770
}

5771 5772
void OBSBasic::on_streamButton_clicked()
{
J
jp9000 已提交
5773
	if (outputHandler->StreamingActive()) {
5774
		bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
J
jp9000 已提交
5775
					       "WarnBeforeStoppingStream");
5776

C
cg2121 已提交
5777
		if (confirm && isVisible()) {
5778
			QMessageBox::StandardButton button =
J
jp9000 已提交
5779 5780
				OBSMessageBox::question(
					this, QTStr("ConfirmStop.Title"),
5781 5782 5783
					QTStr("ConfirmStop.Text"),
					QMessageBox::Yes | QMessageBox::No,
					QMessageBox::No);
5784

C
cg2121 已提交
5785 5786
			if (button == QMessageBox::No) {
				ui->streamButton->setChecked(true);
5787
				return;
C
cg2121 已提交
5788
			}
5789 5790
		}

5791
		StopStreaming();
5792
	} else {
J
JohannMG 已提交
5793
		if (!UIValidation::NoSourcesConfirmation(this)) {
5794 5795 5796 5797
			ui->streamButton->setChecked(false);
			return;
		}

5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811
		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;
		}

5812
		bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
J
jp9000 已提交
5813
					       "WarnBeforeStartingStream");
5814

5815 5816 5817 5818 5819 5820
		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 已提交
5821 5822 5823
				OBSMessageBox::question(
					this, QTStr("ConfirmBWTest.Title"),
					QTStr("ConfirmBWTest.Text"));
5824 5825 5826 5827 5828 5829

			if (button == QMessageBox::No) {
				ui->streamButton->setChecked(false);
				return;
			}
		} else if (confirm && isVisible()) {
5830
			QMessageBox::StandardButton button =
J
jp9000 已提交
5831 5832
				OBSMessageBox::question(
					this, QTStr("ConfirmStart.Title"),
5833 5834 5835
					QTStr("ConfirmStart.Text"),
					QMessageBox::Yes | QMessageBox::No,
					QMessageBox::No);
5836

C
cg2121 已提交
5837 5838
			if (button == QMessageBox::No) {
				ui->streamButton->setChecked(false);
5839
				return;
C
cg2121 已提交
5840
			}
5841 5842
		}

5843
		StartStreaming();
5844 5845 5846 5847 5848
	}
}

void OBSBasic::on_recordButton_clicked()
{
5849
	if (outputHandler->RecordingActive()) {
5850 5851 5852 5853 5854 5855 5856
		bool confirm = config_get_bool(GetGlobalConfig(), "BasicWindow",
					       "WarnBeforeStoppingRecord");

		if (confirm && isVisible()) {
			QMessageBox::StandardButton button =
				OBSMessageBox::question(
					this, QTStr("ConfirmStopRecord.Title"),
5857 5858 5859
					QTStr("ConfirmStopRecord.Text"),
					QMessageBox::Yes | QMessageBox::No,
					QMessageBox::No);
5860 5861 5862 5863 5864 5865

			if (button == QMessageBox::No) {
				ui->recordButton->setChecked(true);
				return;
			}
		}
5866
		StopRecording();
5867
	} else {
J
JohannMG 已提交
5868
		if (!UIValidation::NoSourcesConfirmation(this)) {
5869 5870 5871 5872
			ui->recordButton->setChecked(false);
			return;
		}

5873
		StartRecording();
5874
	}
J
jp9000 已提交
5875 5876
}

J
jp9000 已提交
5877
void OBSBasic::on_settingsButton_clicked()
J
jp9000 已提交
5878
{
J
jp9000 已提交
5879
	on_action_Settings_triggered();
J
jp9000 已提交
5880
}
5881

5882 5883 5884 5885 5886 5887
void OBSBasic::on_actionHelpPortal_triggered()
{
	QUrl url = QUrl("https://obsproject.com/help", QUrl::TolerantMode);
	QDesktopServices::openUrl(url);
}

5888 5889 5890 5891 5892 5893
void OBSBasic::on_actionWebsite_triggered()
{
	QUrl url = QUrl("https://obsproject.com", QUrl::TolerantMode);
	QDesktopServices::openUrl(url);
}

5894 5895
void OBSBasic::on_actionDiscord_triggered()
{
5896
	QUrl url = QUrl("https://obsproject.com/discord", QUrl::TolerantMode);
5897 5898 5899
	QDesktopServices::openUrl(url);
}

5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919
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 已提交
5920
int OBSBasic::GetTopSelectedSourceItem()
5921
{
J
jp9000 已提交
5922 5923 5924
	QModelIndexList selectedItems =
		ui->sources->selectionModel()->selectedIndexes();
	return selectedItems.count() ? selectedItems[0].row() : -1;
5925 5926
}

5927 5928 5929 5930 5931
QModelIndexList OBSBasic::GetAllSelectedSourceItems()
{
	return ui->sources->selectionModel()->selectedIndexes();
}

J
jp9000 已提交
5932 5933
void OBSBasic::on_preview_customContextMenuRequested(const QPoint &pos)
{
5934
	CreateSourcePopupMenu(GetTopSelectedSourceItem(), true);
J
jp9000 已提交
5935 5936 5937 5938

	UNUSED_PARAMETER(pos);
}

J
jp9000 已提交
5939
void OBSBasic::on_program_customContextMenuRequested(const QPoint &)
R
Ryan Foster 已提交
5940 5941 5942 5943
{
	QMenu popup(this);
	QPointer<QMenu> studioProgramProjector;

J
jp9000 已提交
5944
	studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
R
Ryan Foster 已提交
5945
	AddProjectorMenuMonitors(studioProgramProjector, this,
J
jp9000 已提交
5946
				 SLOT(OpenStudioProgramProjector()));
R
Ryan Foster 已提交
5947 5948 5949

	popup.addMenu(studioProgramProjector);

J
jp9000 已提交
5950 5951 5952
	QAction *studioProgramWindow =
		popup.addAction(QTStr("StudioProgramWindow"), this,
				SLOT(OpenStudioProgramWindow()));
R
Ryan Foster 已提交
5953 5954 5955 5956 5957 5958

	popup.addAction(studioProgramWindow);

	popup.exec(QCursor::pos());
}

5959
void OBSBasic::PreviewDisabledMenu(const QPoint &pos)
J
jp9000 已提交
5960 5961
{
	QMenu popup(this);
P
pkv 已提交
5962
	delete previewProjectorMain;
J
jp9000 已提交
5963

J
jp9000 已提交
5964 5965 5966
	QAction *action =
		popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"),
				this, SLOT(TogglePreview()));
J
jp9000 已提交
5967
	action->setCheckable(true);
5968
	action->setChecked(obs_display_enabled(ui->preview->GetDisplay()));
J
jp9000 已提交
5969

P
pkv 已提交
5970 5971
	previewProjectorMain = new QMenu(QTStr("PreviewProjector"));
	AddProjectorMenuMonitors(previewProjectorMain, this,
J
jp9000 已提交
5972
				 SLOT(OpenPreviewProjector()));
J
jp9000 已提交
5973

J
jp9000 已提交
5974 5975
	QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this,
						 SLOT(OpenPreviewWindow()));
C
cg2121 已提交
5976

P
pkv 已提交
5977
	popup.addMenu(previewProjectorMain);
C
cg2121 已提交
5978
	popup.addAction(previewWindow);
J
jp9000 已提交
5979 5980 5981 5982 5983
	popup.exec(QCursor::pos());

	UNUSED_PARAMETER(pos);
}

5984 5985
void OBSBasic::on_actionAlwaysOnTop_triggered()
{
5986
#ifndef _WIN32
5987 5988 5989 5990
	/* 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 */
5991 5992 5993
	CloseDialogs();
#endif

5994
	QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop",
J
jp9000 已提交
5995
				  Qt::QueuedConnection);
5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007
}

void OBSBasic::ToggleAlwaysOnTop()
{
	bool isAlwaysOnTop = IsAlwaysOnTop(this);

	ui->actionAlwaysOnTop->setChecked(!isAlwaysOnTop);
	SetAlwaysOnTop(this, !isAlwaysOnTop);

	show();
}

6008 6009 6010 6011 6012 6013 6014 6015 6016 6017
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 已提交
6018 6019 6020
	} else if (strcmp(val, "24 NTSC") == 0) {
		num = 24000;
		den = 1001;
6021
	} else if (strcmp(val, "25 PAL") == 0) {
6022 6023 6024 6025 6026 6027 6028 6029
		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;
6030 6031 6032
	} else if (strcmp(val, "50 PAL") == 0) {
		num = 50;
		den = 1;
6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076
	} 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);
}

6077
config_t *OBSBasic::Config() const
6078 6079 6080
{
	return basicConfig;
}
J
jp9000 已提交
6081 6082 6083

void OBSBasic::on_actionEditTransform_triggered()
{
6084 6085 6086
	if (transformWindow)
		transformWindow->close();

J
jp9000 已提交
6087 6088
	transformWindow = new OBSBasicTransform(this);
	transformWindow->show();
6089
	transformWindow->setAttribute(Qt::WA_DeleteOnClose, true);
J
jp9000 已提交
6090 6091
}

6092 6093 6094 6095 6096
static obs_transform_info copiedTransformInfo;
static obs_sceneitem_crop copiedCropInfo;

void OBSBasic::on_actionCopyTransform_triggered()
{
J
jp9000 已提交
6097
	auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116
		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 已提交
6117
	auto func = [](obs_scene_t *scene, obs_sceneitem_t *item, void *param) {
6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133
		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);
}

6134
static bool reset_tr(obs_scene_t *scene, obs_sceneitem_t *item, void *param)
J
jp9000 已提交
6135
{
6136 6137 6138 6139
	if (obs_sceneitem_is_group(item))
		obs_sceneitem_group_enum_items(item, reset_tr, nullptr);
	if (!obs_sceneitem_selected(item))
		return true;
J
jp9000 已提交
6140

6141
	obs_sceneitem_defer_update_begin(item);
J
jp9000 已提交
6142

6143 6144 6145 6146 6147 6148 6149 6150 6151
	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 已提交
6152

6153 6154
	obs_sceneitem_crop crop = {};
	obs_sceneitem_set_crop(item, &crop);
J
jp9000 已提交
6155

6156
	obs_sceneitem_defer_update_end(item);
J
jp9000 已提交
6157

6158 6159 6160 6161
	UNUSED_PARAMETER(scene);
	UNUSED_PARAMETER(param);
	return true;
}
J
jp9000 已提交
6162

6163 6164 6165
void OBSBasic::on_actionResetTransform_triggered()
{
	obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr);
J
jp9000 已提交
6166 6167
}

6168
static void GetItemBox(obs_sceneitem_t *item, vec3 &tl, vec3 &br)
J
jp9000 已提交
6169 6170 6171 6172 6173
{
	matrix4 boxTransform;
	obs_sceneitem_get_box_transform(item, &boxTransform);

	vec3_set(&tl, M_INFINITE, M_INFINITE, 0.0f);
6174
	vec3_set(&br, -M_INFINITE, -M_INFINITE, 0.0f);
J
jp9000 已提交
6175

J
jp9000 已提交
6176
	auto GetMinPos = [&](float x, float y) {
J
jp9000 已提交
6177 6178 6179
		vec3 pos;
		vec3_set(&pos, x, y, 0.0f);
		vec3_transform(&pos, &pos, &boxTransform);
6180 6181
		vec3_min(&tl, &tl, &pos);
		vec3_max(&br, &br, &pos);
J
jp9000 已提交
6182 6183
	};

6184 6185 6186 6187 6188 6189
	GetMinPos(0.0f, 0.0f);
	GetMinPos(1.0f, 0.0f);
	GetMinPos(0.0f, 1.0f);
	GetMinPos(1.0f, 1.0f);
}

6190
static vec3 GetItemTL(obs_sceneitem_t *item)
6191 6192 6193
{
	vec3 tl, br;
	GetItemBox(item, tl, br);
J
jp9000 已提交
6194 6195 6196
	return tl;
}

6197
static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl)
J
jp9000 已提交
6198 6199 6200 6201
{
	vec3 newTL;
	vec2 pos;

J
jp9000 已提交
6202
	obs_sceneitem_get_pos(item, &pos);
J
jp9000 已提交
6203 6204 6205
	newTL = GetItemTL(item);
	pos.x += tl.x - newTL.x;
	pos.y += tl.y - newTL.y;
J
jp9000 已提交
6206
	obs_sceneitem_set_pos(item, &pos);
J
jp9000 已提交
6207 6208
}

6209
static bool RotateSelectedSources(obs_scene_t *scene, obs_sceneitem_t *item,
J
jp9000 已提交
6210
				  void *param)
J
jp9000 已提交
6211
{
6212 6213
	if (obs_sceneitem_is_group(item))
		obs_sceneitem_group_enum_items(item, RotateSelectedSources,
J
jp9000 已提交
6214
					       param);
J
jp9000 已提交
6215 6216 6217
	if (!obs_sceneitem_selected(item))
		return true;

J
jp9000 已提交
6218
	float rot = *reinterpret_cast<float *>(param);
J
jp9000 已提交
6219 6220 6221

	vec3 tl = GetItemTL(item);

J
jp9000 已提交
6222
	rot += obs_sceneitem_get_rot(item);
J
jp9000 已提交
6223 6224 6225 6226
	if (rot >= 360.0f)
		rot -= 360.0f;
	else if (rot <= -360.0f)
		rot += 360.0f;
J
jp9000 已提交
6227
	obs_sceneitem_set_rot(item, rot);
J
jp9000 已提交
6228

6229 6230
	obs_sceneitem_force_update_transform(item);

J
jp9000 已提交
6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254
	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);
}

6255
static bool MultiplySelectedItemScale(obs_scene_t *scene, obs_sceneitem_t *item,
J
jp9000 已提交
6256
				      void *param)
J
jp9000 已提交
6257
{
J
jp9000 已提交
6258
	vec2 &mul = *reinterpret_cast<vec2 *>(param);
J
jp9000 已提交
6259

6260 6261
	if (obs_sceneitem_is_group(item))
		obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale,
J
jp9000 已提交
6262
					       param);
J
jp9000 已提交
6263 6264 6265 6266 6267 6268
	if (!obs_sceneitem_selected(item))
		return true;

	vec3 tl = GetItemTL(item);

	vec2 scale;
J
jp9000 已提交
6269
	obs_sceneitem_get_scale(item, &scale);
J
jp9000 已提交
6270
	vec2_mul(&scale, &scale, &mul);
J
jp9000 已提交
6271
	obs_sceneitem_set_scale(item, &scale);
J
jp9000 已提交
6272

6273 6274
	obs_sceneitem_force_update_transform(item);

J
jp9000 已提交
6275
	SetItemTL(item, tl);
J
jp9000 已提交
6276 6277

	UNUSED_PARAMETER(scene);
J
jp9000 已提交
6278 6279 6280 6281 6282
	return true;
}

void OBSBasic::on_actionFlipHorizontal_triggered()
{
J
jp9000 已提交
6283 6284
	vec2 scale;
	vec2_set(&scale, -1.0f, 1.0f);
J
jp9000 已提交
6285
	obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
J
jp9000 已提交
6286
			     &scale);
J
jp9000 已提交
6287 6288 6289 6290
}

void OBSBasic::on_actionFlipVertical_triggered()
{
J
jp9000 已提交
6291 6292
	vec2 scale;
	vec2_set(&scale, 1.0f, -1.0f);
J
jp9000 已提交
6293
	obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale,
J
jp9000 已提交
6294
			     &scale);
J
jp9000 已提交
6295 6296
}

6297
static bool CenterAlignSelectedItems(obs_scene_t *scene, obs_sceneitem_t *item,
J
jp9000 已提交
6298
				     void *param)
J
jp9000 已提交
6299
{
J
jp9000 已提交
6300 6301
	obs_bounds_type boundsType =
		*reinterpret_cast<obs_bounds_type *>(param);
J
jp9000 已提交
6302

6303 6304
	if (obs_sceneitem_is_group(item))
		obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems,
J
jp9000 已提交
6305
					       param);
J
jp9000 已提交
6306 6307 6308 6309 6310 6311
	if (!obs_sceneitem_selected(item))
		return true;

	obs_video_info ovi;
	obs_get_video_info(&ovi);

6312
	obs_transform_info itemInfo;
J
jp9000 已提交
6313 6314 6315 6316 6317
	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 已提交
6318 6319
	vec2_set(&itemInfo.bounds, float(ovi.base_width),
		 float(ovi.base_height));
J
jp9000 已提交
6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332
	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 已提交
6333
			     &boundsType);
J
jp9000 已提交
6334 6335 6336 6337 6338 6339
}

void OBSBasic::on_actionStretchToScreen_triggered()
{
	obs_bounds_type boundsType = OBS_BOUNDS_STRETCH;
	obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems,
J
jp9000 已提交
6340
			     &boundsType);
J
jp9000 已提交
6341 6342
}

6343 6344 6345
enum class CenterType {
	Scene,
	Vertical,
J
jp9000 已提交
6346
	Horizontal,
6347 6348 6349
};

static bool center_to_scene(obs_scene_t *, obs_sceneitem_t *item, void *param)
J
jp9000 已提交
6350
{
J
jp9000 已提交
6351
	CenterType centerType = *reinterpret_cast<CenterType *>(param);
6352

6353 6354
	vec3 tl, br, itemCenter, screenCenter, offset;
	obs_video_info ovi;
6355
	obs_transform_info oti;
6356

6357
	if (obs_sceneitem_is_group(item))
6358
		obs_sceneitem_group_enum_items(item, center_to_scene,
J
jp9000 已提交
6359
					       &centerType);
6360 6361
	if (!obs_sceneitem_selected(item))
		return true;
6362

6363
	obs_get_video_info(&ovi);
6364 6365 6366 6367
	obs_sceneitem_get_info(item, &oti);

	if (centerType == CenterType::Scene)
		vec3_set(&screenCenter, float(ovi.base_width),
J
jp9000 已提交
6368
			 float(ovi.base_height), 0.0f);
6369 6370
	else if (centerType == CenterType::Vertical)
		vec3_set(&screenCenter, float(oti.bounds.x),
J
jp9000 已提交
6371
			 float(ovi.base_height), 0.0f);
6372 6373
	else if (centerType == CenterType::Horizontal)
		vec3_set(&screenCenter, float(ovi.base_width),
J
jp9000 已提交
6374
			 float(oti.bounds.y), 0.0f);
6375

6376
	vec3_mulf(&screenCenter, &screenCenter, 0.5f);
6377

6378
	GetItemBox(item, tl, br);
6379

6380 6381 6382
	vec3_sub(&itemCenter, &br, &tl);
	vec3_mulf(&itemCenter, &itemCenter, 0.5f);
	vec3_add(&itemCenter, &itemCenter, &tl);
6383

6384 6385
	vec3_sub(&offset, &screenCenter, &itemCenter);
	vec3_add(&tl, &tl, &offset);
6386

6387 6388 6389 6390 6391
	if (centerType == CenterType::Vertical)
		tl.x = oti.pos.x;
	else if (centerType == CenterType::Horizontal)
		tl.y = oti.pos.y;

6392 6393 6394
	SetItemTL(item, tl);
	return true;
};
6395

6396 6397
void OBSBasic::on_actionCenterToScreen_triggered()
{
6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411
	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 已提交
6412
}
J
jp9000 已提交
6413

6414 6415 6416 6417
void OBSBasic::EnablePreviewDisplay(bool enable)
{
	obs_display_set_enabled(ui->preview->GetDisplay(), enable);
	ui->preview->setVisible(enable);
6418
	ui->previewDisabledWidget->setVisible(!enable);
6419 6420
}

J
jp9000 已提交
6421 6422
void OBSBasic::TogglePreview()
{
6423 6424
	previewEnabled = !previewEnabled;
	EnablePreviewDisplay(previewEnabled);
J
jp9000 已提交
6425
}
6426

6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444
void OBSBasic::EnablePreview()
{
	if (previewProgramMode)
		return;

	previewEnabled = true;
	EnablePreviewDisplay(true);
}

void OBSBasic::DisablePreview()
{
	if (previewProgramMode)
		return;

	previewEnabled = false;
	EnablePreviewDisplay(false);
}

J
jp9000 已提交
6445
static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param)
6446
{
J
jp9000 已提交
6447 6448
	if (obs_sceneitem_locked(item))
		return true;
6449

J
jp9000 已提交
6450
	struct vec2 &offset = *reinterpret_cast<struct vec2 *>(param);
J
jp9000 已提交
6451
	struct vec2 pos;
6452

J
jp9000 已提交
6453
	if (!obs_sceneitem_selected(item)) {
J
jp9000 已提交
6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466
		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 已提交
6467
						       &new_offset);
J
jp9000 已提交
6468 6469
		}

J
jp9000 已提交
6470 6471
		return true;
	}
6472

J
jp9000 已提交
6473 6474 6475 6476 6477
	obs_sceneitem_get_pos(item, &pos);
	vec2_add(&pos, &pos, &offset);
	obs_sceneitem_set_pos(item, &pos);
	return true;
}
J
jp9000 已提交
6478

J
jp9000 已提交
6479 6480 6481 6482
void OBSBasic::Nudge(int dist, MoveDir dir)
{
	if (ui->preview->Locked())
		return;
6483

J
jp9000 已提交
6484 6485
	struct vec2 offset;
	vec2_set(&offset, 0.0f, 0.0f);
6486

J
jp9000 已提交
6487
	switch (dir) {
J
jp9000 已提交
6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499
	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 已提交
6500
	}
6501

J
jp9000 已提交
6502
	obs_scene_enum_items(GetCurrentScene(), nudge_callback, &offset);
6503 6504
}

J
jp9000 已提交
6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520
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 已提交
6521

6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532
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 已提交
6533
OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor,
6534
				      ProjectorType type)
J
jp9000 已提交
6535 6536
{
	/* seriously?  10 monitors? */
C
cg2121 已提交
6537
	if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1)
S
Shaolin 已提交
6538
		return nullptr;
C
cg2121 已提交
6539

J
jp9000 已提交
6540
	OBSProjector *projector =
6541
		new OBSProjector(nullptr, source, monitor, type);
C
cg2121 已提交
6542

6543 6544
	if (projector)
		projectors.emplace_back(projector);
S
Shaolin 已提交
6545 6546

	return projector;
J
jp9000 已提交
6547 6548
}

R
Ryan Foster 已提交
6549 6550 6551
void OBSBasic::OpenStudioProgramProjector()
{
	int monitor = sender()->property("monitor").toInt();
6552
	OpenProjector(nullptr, monitor, ProjectorType::StudioProgram);
R
Ryan Foster 已提交
6553 6554
}

J
jp9000 已提交
6555 6556 6557
void OBSBasic::OpenPreviewProjector()
{
	int monitor = sender()->property("monitor").toInt();
6558
	OpenProjector(nullptr, monitor, ProjectorType::Preview);
J
jp9000 已提交
6559 6560 6561 6562 6563 6564 6565 6566 6567
}

void OBSBasic::OpenSourceProjector()
{
	int monitor = sender()->property("monitor").toInt();
	OBSSceneItem item = GetCurrentSceneItem();
	if (!item)
		return;

6568
	OpenProjector(obs_sceneitem_get_source(item), monitor,
J
jp9000 已提交
6569
		      ProjectorType::Source);
J
jp9000 已提交
6570 6571
}

S
Shaolin 已提交
6572 6573 6574
void OBSBasic::OpenMultiviewProjector()
{
	int monitor = sender()->property("monitor").toInt();
6575
	OpenProjector(nullptr, monitor, ProjectorType::Multiview);
S
Shaolin 已提交
6576 6577
}

J
jp9000 已提交
6578 6579 6580 6581 6582 6583 6584
void OBSBasic::OpenSceneProjector()
{
	int monitor = sender()->property("monitor").toInt();
	OBSScene scene = GetCurrentScene();
	if (!scene)
		return;

6585
	OpenProjector(obs_scene_get_source(scene), monitor,
J
jp9000 已提交
6586
		      ProjectorType::Scene);
C
cg2121 已提交
6587 6588
}

R
Ryan Foster 已提交
6589 6590
void OBSBasic::OpenStudioProgramWindow()
{
6591
	OpenProjector(nullptr, -1, ProjectorType::StudioProgram);
R
Ryan Foster 已提交
6592 6593
}

C
cg2121 已提交
6594 6595
void OBSBasic::OpenPreviewWindow()
{
6596
	OpenProjector(nullptr, -1, ProjectorType::Preview);
C
cg2121 已提交
6597 6598 6599 6600 6601 6602 6603 6604 6605
}

void OBSBasic::OpenSourceWindow()
{
	OBSSceneItem item = GetCurrentSceneItem();
	if (!item)
		return;

	OBSSource source = obs_sceneitem_get_source(item);
S
Shaolin 已提交
6606

6607
	OpenProjector(obs_sceneitem_get_source(item), -1,
J
jp9000 已提交
6608
		      ProjectorType::Source);
C
cg2121 已提交
6609 6610
}

S
Shaolin 已提交
6611 6612
void OBSBasic::OpenMultiviewWindow()
{
6613
	OpenProjector(nullptr, -1, ProjectorType::Multiview);
S
Shaolin 已提交
6614 6615
}

C
cg2121 已提交
6616 6617 6618 6619 6620 6621 6622
void OBSBasic::OpenSceneWindow()
{
	OBSScene scene = GetCurrentScene();
	if (!scene)
		return;

	OBSSource source = obs_scene_get_source(scene);
S
Shaolin 已提交
6623

6624
	OpenProjector(obs_scene_get_source(scene), -1, ProjectorType::Scene);
J
jp9000 已提交
6625
}
6626

C
cg2121 已提交
6627 6628
void OBSBasic::OpenSavedProjectors()
{
6629
	for (SavedProjectorInfo *info : savedProjectorsArray) {
6630 6631 6632 6633 6634 6635 6636
		OpenSavedProjector(info);
	}
}

void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info)
{
	if (info) {
S
Shaolin 已提交
6637
		OBSProjector *projector = nullptr;
6638
		switch (info->type) {
S
Shaolin 已提交
6639
		case ProjectorType::Source:
6640
		case ProjectorType::Scene: {
J
jp9000 已提交
6641 6642
			OBSSource source =
				obs_get_source_by_name(info->name.c_str());
6643
			if (!source)
6644
				return;
C
cg2121 已提交
6645

6646
			projector = OpenProjector(source, info->monitor,
J
jp9000 已提交
6647
						  info->type);
6648 6649 6650

			obs_source_release(source);
			break;
S
Shaolin 已提交
6651
		}
6652
		default: {
S
Shaolin 已提交
6653
			projector = OpenProjector(nullptr, info->monitor,
6654
						  info->type);
6655 6656
			break;
		}
C
cg2121 已提交
6657
		}
S
Shaolin 已提交
6658

6659
		if (projector && !info->geometry.empty() && info->monitor < 0) {
S
Shaolin 已提交
6660
			QByteArray byteArray = QByteArray::fromBase64(
J
jp9000 已提交
6661
				QByteArray(info->geometry.c_str()));
S
Shaolin 已提交
6662
			projector->restoreGeometry(byteArray);
S
Shaolin 已提交
6663

S
Shaolin 已提交
6664 6665 6666
			if (!WindowPositionValid(projector->normalGeometry())) {
				QRect rect = App()->desktop()->geometry();
				projector->setGeometry(QStyle::alignedRect(
J
jp9000 已提交
6667 6668
					Qt::LeftToRight, Qt::AlignCenter,
					size(), rect));
C
cg2121 已提交
6669 6670 6671 6672 6673
			}
		}
	}
}

6674 6675
void OBSBasic::on_actionFullscreenInterface_triggered()
{
6676
	if (!isFullScreen())
6677 6678 6679 6680 6681
		showFullScreen();
	else
		showNormal();
}

6682 6683 6684 6685
void OBSBasic::UpdateTitleBar()
{
	stringstream name;

J
jp9000 已提交
6686 6687 6688 6689
	const char *profile =
		config_get_string(App()->GlobalConfig(), "Basic", "Profile");
	const char *sceneCollection = config_get_string(
		App()->GlobalConfig(), "Basic", "SceneCollection");
J
jp9000 已提交
6690

6691 6692 6693 6694 6695
	name << "OBS ";
	if (previewProgramMode)
		name << "Studio ";

	name << App()->GetVersionString();
6696 6697 6698
	if (App()->IsPortableMode())
		name << " - Portable Mode";

J
jp9000 已提交
6699
	name << " - " << Str("TitleBar.Profile") << ": " << profile;
J
jp9000 已提交
6700
	name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection;
6701 6702 6703

	setWindowTitle(QT_UTF8(name.str().c_str()));
}
J
jp9000 已提交
6704 6705 6706 6707

int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const
{
	char profiles_path[512];
J
jp9000 已提交
6708 6709
	const char *profile =
		config_get_string(App()->GlobalConfig(), "Basic", "ProfileDir");
J
jp9000 已提交
6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727
	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);
}
6728

J
jp9000 已提交
6729
void OBSBasic::on_resetUI_triggered()
6730
{
6731
	/* prune deleted extra docks */
J
jp9000 已提交
6732
	for (int i = extraDocks.size() - 1; i >= 0; i--) {
6733 6734 6735 6736 6737 6738 6739
		if (!extraDocks[i]) {
			extraDocks.removeAt(i);
		}
	}

	if (extraDocks.size()) {
		QMessageBox::StandardButton button = QMessageBox::question(
J
jp9000 已提交
6740 6741
			this, QTStr("ResetUIWarning.Title"),
			QTStr("ResetUIWarning.Text"));
6742 6743 6744 6745 6746 6747

		if (button == QMessageBox::No)
			return;
	}

	/* undock/hide/center extra docks */
J
jp9000 已提交
6748
	for (int i = extraDocks.size() - 1; i >= 0; i--) {
6749 6750 6751
		if (extraDocks[i]) {
			extraDocks[i]->setVisible(true);
			extraDocks[i]->setFloating(true);
J
jp9000 已提交
6752 6753 6754
			extraDocks[i]->move(frameGeometry().topLeft() +
					    rect().center() -
					    extraDocks[i]->rect().center());
6755 6756 6757 6758
			extraDocks[i]->setVisible(false);
		}
	}

J
jp9000 已提交
6759
	restoreState(startingDockLayout);
6760

6761
#if QT_VERSION >= QT_VERSION_CHECK(5, 6, 0)
J
jp9000 已提交
6762 6763 6764 6765 6766 6767 6768 6769 6770 6771
	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 已提交
6772 6773 6774
	QList<QDockWidget *> docks{ui->scenesDock, ui->sourcesDock,
				   ui->mixerDock, ui->transitionsDock,
				   ui->controlsDock};
J
jp9000 已提交
6775

J
jp9000 已提交
6776
	QList<int> sizes{cx22_5, cx22_5, mixerSize, cx5, cx5};
J
jp9000 已提交
6777 6778 6779 6780 6781 6782

	ui->scenesDock->setVisible(true);
	ui->sourcesDock->setVisible(true);
	ui->mixerDock->setVisible(true);
	ui->transitionsDock->setVisible(true);
	ui->controlsDock->setVisible(true);
6783 6784
	statsDock->setVisible(false);
	statsDock->setFloating(true);
J
jp9000 已提交
6785 6786 6787

	resizeDocks(docks, {cy, cy, cy, cy, cy}, Qt::Vertical);
	resizeDocks(docks, sizes, Qt::Horizontal);
6788
#endif
J
jp9000 已提交
6789 6790 6791 6792
}

void OBSBasic::on_lockUI_toggled(bool lock)
{
J
jp9000 已提交
6793 6794 6795
	QDockWidget::DockWidgetFeatures features =
		lock ? QDockWidget::NoDockWidgetFeatures
		     : QDockWidget::AllDockWidgetFeatures;
J
jp9000 已提交
6796

6797 6798 6799 6800 6801 6802 6803 6804
	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);
6805
	statsDock->setFeatures(features);
6806

J
jp9000 已提交
6807
	for (int i = extraDocks.size() - 1; i >= 0; i--) {
6808 6809 6810 6811 6812 6813
		if (!extraDocks[i]) {
			extraDocks.removeAt(i);
		} else {
			extraDocks[i]->setFeatures(features);
		}
	}
6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828
}

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 已提交
6829 6830
	config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowStatusBar",
			visible);
6831
}
J
jp9000 已提交
6832

6833 6834 6835
void OBSBasic::on_toggleSourceIcons_toggled(bool visible)
{
	ui->sources->SetIconsVisible(visible);
6836 6837
	if (advAudioWindow != nullptr)
		advAudioWindow->SetIconsVisible(visible);
6838 6839 6840 6841 6842

	config_set_bool(App()->GlobalConfig(), "BasicWindow", "ShowSourceIcons",
			visible);
}

J
jp9000 已提交
6843 6844 6845 6846 6847
void OBSBasic::on_actionLockPreview_triggered()
{
	ui->preview->ToggleLocked();
	ui->actionLockPreview->setChecked(ui->preview->Locked());
}
C
cg2121 已提交
6848

J
Joseph El-Khouri 已提交
6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864
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);
6865
	action->setVisible(!(ovi.output_width == ovi.base_width &&
J
jp9000 已提交
6866
			     ovi.output_height == ovi.base_height));
J
Joseph El-Khouri 已提交
6867 6868 6869 6870 6871 6872

	UpdatePreviewScalingMenu();
}

void OBSBasic::on_actionScaleWindow_triggered()
{
6873
	ui->preview->SetFixedScaling(false);
J
Joseph El-Khouri 已提交
6874 6875 6876 6877 6878 6879
	ui->preview->ResetScrollingOffset();
	emit ui->preview->DisplayResized();
}

void OBSBasic::on_actionScaleCanvas_triggered()
{
6880 6881
	ui->preview->SetFixedScaling(true);
	ui->preview->SetScalingLevel(0);
J
Joseph El-Khouri 已提交
6882 6883 6884 6885 6886
	emit ui->preview->DisplayResized();
}

void OBSBasic::on_actionScaleOutput_triggered()
{
6887 6888 6889 6890 6891 6892
	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 已提交
6893 6894
	int32_t approxScalingLevel =
		int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY)));
6895 6896
	ui->preview->SetScalingLevel(approxScalingLevel);
	ui->preview->SetScalingAmount(scalingAmount);
J
Joseph El-Khouri 已提交
6897 6898 6899
	emit ui->preview->DisplayResized();
}

C
cg2121 已提交
6900 6901 6902
void OBSBasic::SetShowing(bool showing)
{
	if (!showing && isVisible()) {
J
jp9000 已提交
6903 6904 6905
		config_set_string(App()->GlobalConfig(), "BasicWindow",
				  "geometry",
				  saveGeometry().toBase64().constData());
C
cg2121 已提交
6906

6907 6908 6909 6910 6911 6912 6913 6914 6915
		/* hide all visible child dialogs */
		visDlgPositions.clear();
		if (!visDialogs.isEmpty()) {
			for (QDialog *dlg : visDialogs) {
				visDlgPositions.append(dlg->pos());
				dlg->hide();
			}
		}

6916 6917
		if (showHide)
			showHide->setText(QTStr("Basic.SystemTray.Show"));
C
cg2121 已提交
6918 6919 6920 6921 6922 6923 6924
		QTimer::singleShot(250, this, SLOT(hide()));

		if (previewEnabled)
			EnablePreviewDisplay(false);

		setVisible(false);

6925 6926 6927 6928
#ifdef __APPLE__
		EnableOSXDockIcon(false);
#endif

C
cg2121 已提交
6929
	} else if (showing && !isVisible()) {
6930 6931
		if (showHide)
			showHide->setText(QTStr("Basic.SystemTray.Hide"));
C
cg2121 已提交
6932 6933 6934 6935 6936 6937
		QTimer::singleShot(250, this, SLOT(show()));

		if (previewEnabled)
			EnablePreviewDisplay(true);

		setVisible(true);
6938

6939 6940 6941 6942 6943 6944 6945 6946
#ifdef __APPLE__
		EnableOSXDockIcon(true);
#endif

		/* raise and activate window to ensure it is on top */
		raise();
		activateWindow();

6947 6948 6949 6950 6951 6952 6953 6954 6955
		/* 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();
			}
		}

6956 6957 6958 6959
		/* Unminimize window if it was hidden to tray instead of task
		 * bar. */
		if (sysTrayMinimizeToTray()) {
			Qt::WindowStates state;
J
jp9000 已提交
6960
			state = windowState() & ~Qt::WindowMinimized;
6961 6962 6963
			state |= Qt::WindowActive;
			setWindowState(state);
		}
C
cg2121 已提交
6964 6965 6966
	}
}

6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978
void OBSBasic::ToggleShowHide()
{
	bool showing = isVisible();
	if (showing) {
		/* check for modal dialogs */
		EnumDialogs();
		if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty())
			return;
	}
	SetShowing(!showing);
}

6979 6980
void OBSBasic::SystemTrayInit()
{
J
jp9000 已提交
6981 6982 6983
	trayIcon.reset(new QSystemTrayIcon(
		QIcon::fromTheme("obs-tray", QIcon(":/res/images/obs.png")),
		this));
C
cg2121 已提交
6984 6985
	trayIcon->setToolTip("OBS Studio");

J
jp9000 已提交
6986
	showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data());
C
cg2121 已提交
6987
	sysTrayStream = new QAction(QTStr("Basic.Main.StartStreaming"),
J
jp9000 已提交
6988
				    trayIcon.data());
C
cg2121 已提交
6989
	sysTrayRecord = new QAction(QTStr("Basic.Main.StartRecording"),
J
jp9000 已提交
6990
				    trayIcon.data());
J
jp9000 已提交
6991
	sysTrayReplayBuffer = new QAction(QTStr("Basic.Main.StartReplayBuffer"),
J
jp9000 已提交
6992 6993
					  trayIcon.data());
	exit = new QAction(QTStr("Exit"), trayIcon.data());
C
cg2121 已提交
6994

6995 6996 6997 6998
	trayMenu = new QMenu;
	previewProjector = new QMenu(QTStr("PreviewProjector"));
	studioProgramProjector = new QMenu(QTStr("StudioProgramProjector"));
	AddProjectorMenuMonitors(previewProjector, this,
J
jp9000 已提交
6999
				 SLOT(OpenPreviewProjector()));
7000
	AddProjectorMenuMonitors(studioProgramProjector, this,
J
jp9000 已提交
7001
				 SLOT(OpenStudioProgramProjector()));
7002 7003 7004 7005 7006 7007 7008 7009
	trayMenu->addAction(showHide);
	trayMenu->addMenu(previewProjector);
	trayMenu->addMenu(studioProgramProjector);
	trayMenu->addAction(sysTrayStream);
	trayMenu->addAction(sysTrayRecord);
	trayMenu->addAction(sysTrayReplayBuffer);
	trayMenu->addAction(exit);
	trayIcon->setContextMenu(trayMenu);
7010
	trayIcon->show();
7011

J
jp9000 已提交
7012 7013
	if (outputHandler && !outputHandler->replayBuffer)
		sysTrayReplayBuffer->setEnabled(false);
7014

7015
	connect(trayIcon.data(),
J
jp9000 已提交
7016 7017 7018 7019 7020 7021 7022 7023 7024 7025
		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 已提交
7026 7027 7028 7029
}

void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason)
{
7030 7031 7032 7033
	// Refresh projector list
	previewProjector->clear();
	studioProgramProjector->clear();
	AddProjectorMenuMonitors(previewProjector, this,
J
jp9000 已提交
7034
				 SLOT(OpenPreviewProjector()));
7035
	AddProjectorMenuMonitors(studioProgramProjector, this,
J
jp9000 已提交
7036
				 SLOT(OpenStudioProgramProjector()));
7037 7038

	if (reason == QSystemTrayIcon::Trigger)
C
cg2121 已提交
7039 7040 7041 7042
		ToggleShowHide();
}

void OBSBasic::SysTrayNotify(const QString &text,
J
jp9000 已提交
7043
			     QSystemTrayIcon::MessageIcon n)
C
cg2121 已提交
7044
{
7045
	if (trayIcon && QSystemTrayIcon::supportsMessages()) {
C
cg2121 已提交
7046
		QSystemTrayIcon::MessageIcon icon =
J
jp9000 已提交
7047
			QSystemTrayIcon::MessageIcon(n);
C
cg2121 已提交
7048 7049 7050 7051 7052 7053 7054 7055
		trayIcon->showMessage("OBS Studio", text, icon, 10000);
	}
}

void OBSBasic::SystemTray(bool firstStarted)
{
	if (!QSystemTrayIcon::isSystemTrayAvailable())
		return;
7056
	if (!trayIcon && !firstStarted)
J
jp9000 已提交
7057
		return;
C
cg2121 已提交
7058

J
jp9000 已提交
7059 7060 7061 7062
	bool sysTrayWhenStarted = config_get_bool(
		GetGlobalConfig(), "BasicWindow", "SysTrayWhenStarted");
	bool sysTrayEnabled = config_get_bool(GetGlobalConfig(), "BasicWindow",
					      "SysTrayEnabled");
C
cg2121 已提交
7063 7064 7065 7066 7067 7068

	if (firstStarted)
		SystemTrayInit();

	if (!sysTrayWhenStarted && !sysTrayEnabled) {
		trayIcon->hide();
J
jp9000 已提交
7069 7070
	} else if ((sysTrayWhenStarted && sysTrayEnabled) ||
		   opt_minimize_tray) {
C
cg2121 已提交
7071 7072 7073 7074 7075
		trayIcon->show();
		if (firstStarted) {
			QTimer::singleShot(50, this, SLOT(hide()));
			EnablePreviewDisplay(false);
			setVisible(false);
7076 7077 7078
#ifdef __APPLE__
			EnableOSXDockIcon(false);
#endif
C
cg2121 已提交
7079
			opt_minimize_tray = false;
C
cg2121 已提交
7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093
		}
	} 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"));
}
7094 7095 7096

bool OBSBasic::sysTrayMinimizeToTray()
{
J
jp9000 已提交
7097 7098
	return config_get_bool(GetGlobalConfig(), "BasicWindow",
			       "SysTrayMinimizeToTray");
7099
}
7100 7101 7102

void OBSBasic::on_actionCopySource_triggered()
{
7103 7104
	copyStrings.clear();
	bool allowPastingDuplicate = true;
J
jp9000 已提交
7105

7106 7107 7108 7109
	for (auto &selectedSource : GetAllSelectedSourceItems()) {
		OBSSceneItem item = ui->sources->Get(selectedSource.row());
		if (!item)
			continue;
7110

7111
		on_actionCopyTransform_triggered();
7112

7113
		OBSSource source = obs_sceneitem_get_source(item);
7114

7115
		copyStrings.push_front(obs_source_get_name(source));
7116

7117 7118 7119 7120 7121 7122 7123 7124 7125
		copyVisible = obs_sceneitem_visible(item);

		uint32_t output_flags = obs_source_get_output_flags(source);
		if (!(output_flags & OBS_SOURCE_DO_NOT_DUPLICATE) == 0)
			allowPastingDuplicate = false;
	}

	ui->actionPasteRef->setEnabled(true);
	ui->actionPasteDup->setEnabled(allowPastingDuplicate);
7126 7127 7128 7129
}

void OBSBasic::on_actionPasteRef_triggered()
{
7130 7131 7132 7133 7134
	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 已提交
7135

7136 7137 7138 7139
		OBSBasicSourceSelect::SourcePaste(copyString, copyVisible,
						  false);
		on_actionPasteTransform_triggered();
	}
7140 7141 7142 7143
}

void OBSBasic::on_actionPasteDup_triggered()
{
7144 7145 7146 7147 7148
	for (auto &copyString : copyStrings) {
		OBSBasicSourceSelect::SourcePaste(copyString, copyVisible,
						  true);
		on_actionPasteTransform_triggered();
	}
7149 7150
}

7151 7152
void OBSBasic::AudioMixerCopyFilters()
{
J
jp9000 已提交
7153 7154
	QAction *action = reinterpret_cast<QAction *>(sender());
	VolControl *vol = action->property("volControl").value<VolControl *>();
7155 7156 7157 7158 7159 7160 7161
	obs_source_t *source = vol->GetSource();

	copyFiltersString = obs_source_get_name(source);
}

void OBSBasic::AudioMixerPasteFilters()
{
J
jp9000 已提交
7162 7163
	QAction *action = reinterpret_cast<QAction *>(sender());
	VolControl *vol = action->property("volControl").value<VolControl *>();
7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174
	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);
}

7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192
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);
}

7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209
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);
7210
	obs_source_release(source);
7211

7212
	OBSSceneItem sceneItem = GetCurrentSceneItem();
7213 7214 7215 7216 7217 7218 7219
	OBSSource dstSource = obs_sceneitem_get_source(sceneItem);

	if (source == dstSource)
		return;

	obs_source_copy_filters(dstSource, source);
}
J
jp9000 已提交
7220

7221
static void ConfirmColor(SourceTree *sources, const QColor &color,
J
jp9000 已提交
7222
			 QModelIndexList selectedItems)
7223 7224
{
	for (int x = 0; x < selectedItems.count(); x++) {
J
jp9000 已提交
7225 7226 7227 7228
		SourceTreeItem *treeItem =
			sources->GetItemWidget(selectedItems[x].row());
		treeItem->setStyleSheet("background: " +
					color.name(QColor::HexArgb));
7229 7230 7231
		treeItem->style()->unpolish(treeItem);
		treeItem->style()->polish(treeItem);

J
jp9000 已提交
7232
		OBSSceneItem sceneItem = sources->Get(selectedItems[x].row());
7233 7234 7235 7236
		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 已提交
7237
				    QT_TO_UTF8(color.name(QColor::HexArgb)));
7238 7239 7240 7241 7242 7243 7244 7245
		obs_data_release(privData);
	}
}

void OBSBasic::ColorChange()
{
	QModelIndexList selectedItems =
		ui->sources->selectionModel()->selectedIndexes();
J
jp9000 已提交
7246 7247
	QAction *action = qobject_cast<QAction *>(sender());
	QPushButton *colorButton = qobject_cast<QPushButton *>(sender());
7248 7249 7250 7251 7252 7253 7254 7255

	if (selectedItems.count() == 0)
		return;

	if (colorButton) {
		int preset = colorButton->property("bgColor").value<int>();

		for (int x = 0; x < selectedItems.count(); x++) {
J
jp9000 已提交
7256 7257
			SourceTreeItem *treeItem = ui->sources->GetItemWidget(
				selectedItems[x].row());
7258 7259 7260 7261 7262
			treeItem->setStyleSheet("");
			treeItem->setProperty("bgColor", preset);
			treeItem->style()->unpolish(treeItem);
			treeItem->style()->polish(treeItem);

J
jp9000 已提交
7263 7264
			OBSSceneItem sceneItem =
				ui->sources->Get(selectedItems[x].row());
7265 7266 7267 7268 7269 7270 7271 7272 7273 7274
			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 已提交
7275 7276 7277 7278
			QPushButton *cButton =
				colorButton->parentWidget()
					->findChild<QPushButton *>(
						button.str().c_str());
7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290
			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 已提交
7291 7292
				obs_sceneitem_get_private_settings(
					curSceneItem);
7293

J
jp9000 已提交
7294 7295
			int oldPreset =
				obs_data_get_int(curPrivData, "color-preset");
7296 7297 7298 7299 7300
			const QString oldSheet = curTreeItem->styleSheet();

			auto liveChangeColor = [=](const QColor &color) {
				if (color.isValid()) {
					curTreeItem->setStyleSheet(
J
jp9000 已提交
7301 7302
						"background: " +
						color.name(QColor::HexArgb));
7303 7304 7305 7306 7307 7308
				}
			};

			auto changedColor = [=](const QColor &color) {
				if (color.isValid()) {
					ConfirmColor(ui->sources, color,
J
jp9000 已提交
7309
						     selectedItems);
7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323
				}
			};

			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 已提交
7324
								 oldPreset - 1);
7325 7326 7327 7328 7329 7330 7331 7332 7333
				}

				curTreeItem->style()->unpolish(curTreeItem);
				curTreeItem->style()->polish(curTreeItem);
			};

			QColorDialog::ColorDialogOptions options =
				QColorDialog::ShowAlphaChannel;

J
jp9000 已提交
7334 7335
			const char *oldColor =
				obs_data_get_string(curPrivData, "color");
7336
			const char *customColor = *oldColor != 0 ? oldColor
J
jp9000 已提交
7337
								 : "#55FF0000";
7338 7339 7340 7341 7342 7343
#ifdef __APPLE__
			options |= QColorDialog::DontUseNativeDialog;
#endif

			QColorDialog *colorDialog = new QColorDialog(this);
			colorDialog->setOptions(options);
J
jp9000 已提交
7344
			colorDialog->setCurrentColor(QColor(customColor));
7345
			connect(colorDialog, &QColorDialog::currentColorChanged,
J
jp9000 已提交
7346
				liveChangeColor);
7347
			connect(colorDialog, &QColorDialog::colorSelected,
J
jp9000 已提交
7348 7349
				changedColor);
			connect(colorDialog, &QColorDialog::rejected, rejected);
7350 7351 7352 7353 7354
			colorDialog->open();

			obs_data_release(curPrivData);
		} else {
			for (int x = 0; x < selectedItems.count(); x++) {
J
jp9000 已提交
7355 7356 7357
				SourceTreeItem *treeItem =
					ui->sources->GetItemWidget(
						selectedItems[x].row());
7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368
				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 已提交
7369
						 preset);
7370 7371 7372 7373 7374 7375 7376
				obs_data_set_string(privData, "color", "");
				obs_data_release(privData);
			}
		}
	}
}

J
jp9000 已提交
7377
SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem)
7378 7379 7380 7381 7382 7383 7384 7385 7386 7387
{
	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 已提交
7388
	if (treeItem)
7389 7390 7391 7392 7393
		return treeItem;

	return nullptr;
}

J
jp9000 已提交
7394 7395 7396 7397 7398 7399 7400
void OBSBasic::on_autoConfigure_triggered()
{
	AutoConfig test(this);
	test.setModal(true);
	test.show();
	test.exec();
}
J
jp9000 已提交
7401 7402 7403

void OBSBasic::on_stats_triggered()
{
7404 7405 7406 7407 7408 7409
	if (!stats.isNull()) {
		stats->show();
		stats->raise();
		return;
	}

J
jp9000 已提交
7410 7411 7412 7413 7414
	OBSBasicStats *statsDlg;
	statsDlg = new OBSBasicStats(nullptr);
	statsDlg->show();
	stats = statsDlg;
}
7415

C
cg2121 已提交
7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426
void OBSBasic::on_actionShowAbout_triggered()
{
	if (about)
		about->close();

	about = new OBSAbout(this);
	about->show();

	about->setAttribute(Qt::WA_DeleteOnClose, true);
}

7427 7428
void OBSBasic::ResizeOutputSizeOfSource()
{
7429
	if (obs_video_active())
7430 7431 7432
		return;

	QMessageBox resize_output(this);
J
jp9000 已提交
7433 7434 7435 7436
	resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") + "\n\n" +
			      QTStr("ResizeOutputSizeOfSource.Continue"));
	QAbstractButton *Yes =
		resize_output.addButton(QTStr("Yes"), QMessageBox::YesRole);
7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457
	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();
}
7458

7459 7460 7461 7462 7463 7464 7465 7466
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 已提交
7467 7468 7469
	QDockWidget::DockWidgetFeatures features =
		lock ? QDockWidget::NoDockWidgetFeatures
		     : QDockWidget::AllDockWidgetFeatures;
7470 7471 7472 7473

	dock->setFeatures(features);

	/* prune deleted docks */
J
jp9000 已提交
7474
	for (int i = extraDocks.size() - 1; i >= 0; i--) {
7475 7476 7477 7478 7479 7480 7481 7482
		if (!extraDocks[i]) {
			extraDocks.removeAt(i);
		}
	}

	return action;
}

7483 7484
OBSBasic *OBSBasic::Get()
{
J
jp9000 已提交
7485
	return reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
7486
}
7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507

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();
}
7508 7509 7510 7511 7512 7513 7514

SceneRenameDelegate::SceneRenameDelegate(QObject *parent)
	: QStyledItemDelegate(parent)
{
}

void SceneRenameDelegate::setEditorData(QWidget *editor,
J
jp9000 已提交
7515
					const QModelIndex &index) const
7516 7517
{
	QStyledItemDelegate::setEditorData(editor, index);
J
jp9000 已提交
7518
	QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
7519 7520 7521
	if (lineEdit)
		lineEdit->selectAll();
}
7522 7523 7524 7525 7526 7527

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 已提交
7528
			QLineEdit *lineEdit = qobject_cast<QLineEdit *>(editor);
7529 7530 7531 7532 7533 7534 7535
			if (lineEdit)
				lineEdit->undo();
		}
	}

	return QStyledItemDelegate::eventFilter(editor, event);
}
7536 7537 7538 7539 7540 7541 7542 7543

void OBSBasic::UpdatePatronJson(const QString &text, const QString &error)
{
	if (!error.isEmpty())
		return;

	patronJson = QT_TO_UTF8(text);
}
J
jp9000 已提交
7544 7545 7546 7547 7548 7549 7550 7551 7552

void OBSBasic::PauseRecording()
{
	if (!pause || !outputHandler || !outputHandler->fileOutput)
		return;

	obs_output_t *output = outputHandler->fileOutput;

	if (obs_output_pause(output, true)) {
7553 7554
		pause->setAccessibleName(QTStr("Basic.Main.UnpauseRecording"));
		pause->setToolTip(QTStr("Basic.Main.UnpauseRecording"));
7555
		pause->blockSignals(true);
J
jp9000 已提交
7556
		pause->setChecked(true);
7557
		pause->blockSignals(false);
7558 7559 7560 7561

		if (trayIcon)
			trayIcon->setIcon(QIcon(":/res/images/obs_paused.png"));

J
jp9000 已提交
7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574 7575 7576 7577 7578 7579
		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)) {
7580 7581
		pause->setAccessibleName(QTStr("Basic.Main.PauseRecording"));
		pause->setToolTip(QTStr("Basic.Main.PauseRecording"));
7582
		pause->blockSignals(true);
J
jp9000 已提交
7583
		pause->setChecked(false);
7584
		pause->blockSignals(false);
7585 7586 7587 7588 7589

		if (trayIcon)
			trayIcon->setIcon(
				QIcon(":/res/images/tray_active.png"));

J
jp9000 已提交
7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604
		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);

7605 7606 7607 7608
	if (enable)
		PauseRecording();
	else
		UnpauseRecording();
J
jp9000 已提交
7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647
}

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")));
7648
		connect(pause.data(), &QAbstractButton::clicked, this,
J
jp9000 已提交
7649 7650 7651 7652 7653 7654
			&OBSBasic::PauseToggled);
		ui->recordingLayout->addWidget(pause.data());
	} else {
		pause.reset();
	}
}
7655

7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675
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());
}

7676 7677 7678 7679
#define MBYTE (1024ULL * 1024ULL)
#define MBYTES_LEFT_STOP_REC 50ULL
#define MAX_BYTES_LEFT (MBYTES_LEFT_STOP_REC * MBYTE)

7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702
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;
}

7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716
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();
}

7717 7718 7719 7720 7721 7722 7723 7724 7725 7726
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()
{
7727 7728 7729 7730 7731
	const char *path;

	path = GetCurrentOutputPath();
	if (!path)
		return false;
7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749

	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();
	}
}
7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761

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 已提交
7762 7763 7764 7765 7766 7767 7768

void OBSBasic::ResetStatsHotkey()
{
	QList<OBSBasicStats *> list = findChildren<OBSBasicStats *>();

	foreach(OBSBasicStats * s, list) s->Reset();
}