~mhall119/ubuntu-app-reviews/qtranscribe

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
/*
 *  Copyright © 2012 Matt Pharoah (mr.exuberant@gmail.com)
 *
 *  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
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  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/>.
 *
 */

#include "Dictation.hh"
#include "Joystick.hh"
#include "Actions.hh"

#include <sys/stat.h>

#include <cstdio>
#include <thread>
#include <mutex>
#include <chrono>
#include <cstdlib>
#include <fstream>

#include <QThread>
#include <QApplication>
#include <QMainWindow>
#include <QObject>
#include <QIcon>
#include <QFileDialog>
#include <QString>
#include <QMessageBox>
#include <QTimer>
#include <QModelIndex>
#include <QDialog>

#include "ui_mainWindow.h"
#include "ui_optionsWindow.h"
#include "ui_footPedalWindow.h"
#include "ui_command.h"
#include "ui_notConfiguredMessage.h"
#include "footPedalWidgetModels.hh"
#include "QHandler.hh"

#include <sox.h>

static Joystick *J = NULL;
static Dictation *D = NULL;

static thread *waitForConnection = NULL;
volatile static bool joystickFound = false;
static mutex jsearch;

static Ui::MainWindow *win;
static Ui::optionsWindow *opWin;
static Ui::footPedalWindow *fpcWin;

static int EXTRAS_SIZE;

static volatile bool windowClosed = false;
static bool adjustingTimer = false;
static bool paused = true;
static bool pedalFocus = true;
static bool slowed = false;

static QIcon playIcon;
static QIcon pauseIcon;

static QHandler handler;
static volatile bool *SoXError;

static mutex timeLock;
static mutex dictationLock;
static mutex joystickCommandLock;

static int PLAY_SKIPBACK = -1000;
static float SLOW_SPEED = 0.5;

static string configFile;
static string joystickFile;

static FootPedalListModel fplModel;
static PedalCommandTable fpctModel;

static Action pedalCommand[256];

static void trim(char *str) {
	int i = -1; while (str[++i] != '\0');
	while(i > 0 && (str[--i] == ' ' || str[i] == '\t')) str[i] = '\0';
}

static void saveConfigFile() {
	FILE *conf = fopen(configFile.c_str(), "w");
	if (conf != NULL) {
		fprintf(conf, "Rewind / Fast Forward Sound Effects = %d\n", (int) opWin->soundEffectsCheckbox->isChecked());
		fprintf(conf, "Playback Skip = %d\n", PLAY_SKIPBACK);
		fprintf(conf, "Rewind Speed = %d\n", Dictation::getRewindSpeed());
		fprintf(conf, "Fast Forward Speed = %d\n", Dictation::getFastForwardSpeed());
		fprintf(conf, "Slow Speed = %f\n", SLOW_SPEED);
		fclose(conf);
	}
}

static void notifyJoystickSelectionChanged(const QModelIndex &index) {
	QMetaObject::invokeMethod(fpcWin->deviceList, "setCurrentIndex", Qt::QueuedConnection, Q_ARG(QModelIndex, index));
	QMetaObject::invokeMethod(&handler, "deviceSelected", Qt::QueuedConnection, Q_ARG(QModelIndex, index), Q_ARG(QModelIndex, QModelIndex()));
}

class OWindow : public QMainWindow {
  public:
	OWindow(): QMainWindow() {};
  protected:
	void closeEvent(QCloseEvent *ev) {
		saveConfigFile();
	}
};
static OWindow *optionsWindow;

class CWindow : public QMainWindow {
  private:
	QBasicTimer refresh;
  public:
	CWindow() : QMainWindow() {};
	~CWindow() {
		refresh.stop();
	}
  protected:
	void showEvent(QShowEvent *ev) {
		jsearch.lock();
		joystickFound = true;
		jsearch.unlock();
		pedalFocus = false;
		fplModel.recheck();
		if (J != NULL) {
			char ID[258];
			ID[0] = J->getPort() + 1;
			try {
				Joystick::getNameAndButtons(ID[0] - 1, &ID[2], 256, (unsigned char *) &ID[1]);
				notifyJoystickSelectionChanged(fplModel.find(ID));
			} catch (invalid_argument &e) {
				notifyJoystickSelectionChanged(QModelIndex());
			}
		} else {
			QMetaObject::invokeMethod(fpcWin->deviceList, "setCurrentIndex", Qt::QueuedConnection, Q_ARG(QModelIndex, QModelIndex()));
		}
		refresh.start(1000, &fplModel);
	}
	void closeEvent(QCloseEvent *ev) {
		pedalFocus = true;
		refresh.stop();
		fpctModel.changeJoystick(0xff, 0); //causes the joystick polling for the config window to cease
	}
};
static CWindow *footPedalConfigWindow;

class Window : public QMainWindow {
  public:
	Window(): QMainWindow() {};
  protected:
	void closeEvent(QCloseEvent *ev) {
		saveConfigFile();
		optionsWindow->close();
		footPedalConfigWindow->close();
		windowClosed = true;
	}
};
static Window *root;

static Action getCommand(const char *msg, Action def) {
	Ui::dialogBox commandView;
	QDialog dial;
	commandView.setupUi(&dial);
	commandView.comment->setText(QString(msg));
	for (int a = 0; a < NUM_ACTIONS; a++) commandView.commandBox->addItem(QString(ACTION_STRING(ACTION_NUM(a))), QVariant(a));
	commandView.commandBox->setCurrentIndex(def);
	if (dial.exec() == QDialog::Accepted) {
		return ACTION_NUM(commandView.commandBox->currentIndex());
	} else return def;
}

/*
 * IMPORTANT! Remember to close IF_OPEN with ENDIF_OPEN and ensure
 * that control will always reach ENDIF_OPEN to prevent deadlock
 */
#define IF_OPEN \
	dictationLock.lock(); \
	if (D == NULL) { \
		dictationLock.unlock(); \
		return; \
	}
#define ENDIF_OPEN dictationLock.unlock();

static inline void clearPedalInfo() {
	for (short i = 0; i < 256; i++) pedalCommand[i] = A_NOOP;
	IF_OPEN
	D->setSpeed(1.f);
	D->stopRewind();
	D->stopFastForward();
	D->pause();
	slowed = false;
	ENDIF_OPEN
}

static void eventListener(const JSEvent &ev, void *userdata) {
	IF_OPEN
	joystickCommandLock.lock();
	if (pedalFocus && !adjustingTimer && ev.type == Joystick::BUTTON_EVENT && (ev.value == Joystick::RELEASED || ev.value == Joystick::PRESSED)) {
		if (ev.value == Joystick::PRESSED) {
			switch (pedalCommand[ev.button]) {
				case A_PLAY: D->skipForward(PLAY_SKIPBACK); D->play(); break;
				case A_REWIND: D->startRewind(); break;
				case A_FAST_FORWARD: D->startFastForward(); break;
				case A_SLOW_TOGGLE: if (slowed) {D->setSpeed(1.f);} else D->setSpeed(SLOW_SPEED); slowed = !slowed; break;
				case A_SLOW_PLAY: D->setSpeed(SLOW_SPEED); D->skipForward(PLAY_SKIPBACK); D->play(); break;
				case A_BACK1: D->skipForward(-1000); break;
				case A_BACK5: D->skipForward(-5000); break;
				case A_BACK10: D->skipForward(-10000); break;
				default: break; //make the compiler happy
			}
		} else {
			switch (pedalCommand[ev.button]) {
				case A_PLAY: D->pause(); break;
				case A_REWIND: D->stopRewind(); break;
				case A_FAST_FORWARD: D->stopFastForward(); break;
				case A_SLOW_PLAY: D->setSpeed(1.f); D->pause(); break;
				default: break; //make the compiler happy
			}
		}
	}
	joystickCommandLock.unlock();
	ENDIF_OPEN
}

/*
 * returns true iff the file could be opened (even if the file is empty)
 * If name is non-null, copies the name of the joystick into name, or an
 * empty string if the joystick name could not be loaded from the file
 */
static bool loadFootpedalConfig(char *name = NULL) {
	if (J != NULL) {
		delete J;
		J = NULL;
	}
	if (name != NULL) name[0] = '\0';
	FILE *jfile = fopen(joystickFile.c_str(), "r");
	if (jfile != NULL) {
		char jname[257]; char line[256];
		if (fgets(jname, 257, jfile) == NULL) return true;
		for (short i = 0; i < 255; i++) {
			if (jname[i] == '\n') {
				jname[i] = '\0';
				break;
			}
		}
		jname[255] = '\0';
		if (name != NULL) strcpy(name, jname);
		if (fgets(line, 256, jfile) == NULL) return true;
		unsigned char jbuttons = atoi(line);
		char id[256]; unsigned char b;
		joystickCommandLock.lock();
		for (unsigned char i = 0; i <= 9; i++) {
			try {
				Joystick::getNameAndButtons(i, id, 256, &b);
				if (jbuttons == b && strcmp(jname, id) == 0) {
					J = new Joystick(i, eventListener);
					break;
				}
			} catch (const invalid_argument& e) {};
		}
		for (unsigned char i = 0; i < jbuttons; i++) {
			if (fgets(line, 256, jfile) != NULL) {
				pedalCommand[i] = ACTION_NUM(atoi(line));
				fpctModel.changeCommand(i, pedalCommand[i]);
			} else {
				pedalCommand[i] = A_NOOP;
			}
		}
		for (unsigned short i = jbuttons; i < 256; i++) pedalCommand[i] = A_NOOP;
		joystickCommandLock.unlock();
		return true;
	} else return false;
}

/*
 * Qt Main Window Widget Listeners
 */
static bool playingBeforeAdjust;

void QHandler::timeSliderPressed() {
	IF_OPEN
	playingBeforeAdjust = !D->isPaused();
	D->pause();
	adjustingTimer = true;
	ENDIF_OPEN
}

void QHandler::timeSliderReleased() {
	IF_OPEN
	timeLock.lock();
	D->setPositionMilliseconds((unsigned int) win->timeSlider->sliderPosition());
	if (playingBeforeAdjust) D->play();
	adjustingTimer = false;
	timeLock.unlock();
	ENDIF_OPEN
}

void QHandler::playPauseButtonClicked() {
	IF_OPEN
	if (D->isPaused()) {
		D->skipForward(PLAY_SKIPBACK);
		D->play();
	} else {
		D->pause();
	}
	ENDIF_OPEN
}

void QHandler::restartButtonClicked() {
	IF_OPEN
	D->setPositionMilliseconds(0);
	ENDIF_OPEN
}

void QHandler::back10ButtonClicked() {
	IF_OPEN
	D->skipForward(-10000);
	ENDIF_OPEN
}

void QHandler::back5ButtonClicked() {
	IF_OPEN
	D->skipForward(-5000);
	ENDIF_OPEN
}

void QHandler::slowButtonClicked() {
	IF_OPEN
	if (slowed) {
		D->setSpeed(1.0);
	} else {
		D->setSpeed(SLOW_SPEED);
	}
	slowed = !slowed;
	ENDIF_OPEN
}

void QHandler::rewindButtonPressed() {
	IF_OPEN
	D->startRewind();
	ENDIF_OPEN
}

void QHandler::rewindButtonReleased() {
	IF_OPEN
	D->stopRewind();
	ENDIF_OPEN
}

void QHandler::fastForwardButtonPressed() {
	IF_OPEN
	D->startFastForward();
	ENDIF_OPEN
}

void QHandler::fastForwardButtonReleased() {
	IF_OPEN
	D->stopFastForward();
	ENDIF_OPEN
}

void QHandler::openFileButtonClicked() {
	/*
	 * I SUPPOSE I could rewrite the dictation class to support
	 * changing audio files, but for now I just associate each
	 * Dictation with only one file, then delete it and create
	 * a new one when switching files. It's just easier to code,
	 * and the inefficiency doesn't matter since it's not like
	 * you're switching audio files every few milliseconds!
	 */
	dictationLock.lock();
	string documents = getenv("HOME");
	documents += "/Documents";
	string file = QFileDialog::getOpenFileName(NULL, QString("Open Audio File"), QString(documents.c_str()), tr("Supported Audio Files (*.ogg *.wav *.flac *.aiff *.aif *.aifc *.au *.snd *.iff *.8svx *.pvf *.caf *.mp3);; All Files (*)")).toStdString();

	if (file != "") {
		timeLock.lock();
		delete D;
		try {
			D = new Dictation(file, SoXError);
		} catch (exception &e) {
			QMessageBox::critical(root, QString("Error"), QString(e.what()));
			D = NULL;
			win->fileNameLabel->setText(QString("Nothing"));
			win->positionLabel->setText(QString(" 0:00"));
			win->durationLabel->setText(QString(" 0:00"));
			win->timeSlider->setRange(0, 60000);
			timeLock.unlock();
			dictationLock.unlock();
			return;
		}

		unsigned int len = D->getLengthMilliseconds() / 1000;
		char length[6];
		sprintf(length, "%2d:%02d", len / 60, len % 60);
		win->durationLabel->setText(length);
		win->timeSlider->setRange(0, D->getLengthMilliseconds());
		win->fileNameLabel->setText(QString(file.substr(file.find_last_of('/') + 1).c_str()));
		timeLock.unlock();
	}
	dictationLock.unlock();
}

void QHandler::optionsButtonClicked() {
	optionsWindow->show();
}

void QHandler::pedalConfigButtonClicked() {
	footPedalConfigWindow->show();
}

void QHandler::showExtrasButtonClicked() {
	const bool visibility = !win->extraStuff->isVisible();
	if (visibility) root->setFixedWidth(root->width() + EXTRAS_SIZE);
	win->extraStuff->setVisible(visibility);
	win->showExtrasButton->setChecked(visibility);
	if (!visibility) root->setFixedWidth(root->width() - EXTRAS_SIZE);
}

/*
 * Qt Options Window Widget Listeners
 */

void QHandler::joystickConfigButtonClicked() {
	footPedalConfigWindow->show();
}

void QHandler::soundEffectsCheckboxClicked(bool checked) {
	Dictation::setEffectsEnabled(checked);
}

void QHandler::skipOnPlayCheckboxClicked(bool checked) {
	opWin->skipOnPlayDelay->setEnabled(checked);
	if (checked) {
		PLAY_SKIPBACK = -1 * opWin->skipOnPlayDelay->value();
	} else {
		PLAY_SKIPBACK = 0;
	}
}

void QHandler::skipOnPlaySpinnerChanged(int ms) {
	PLAY_SKIPBACK = -1 * ms;
}

void QHandler::rewindSpeedSliderChanged(int exp) {
	int mult;
	if (exp == 0) {
		mult = 1;
	} else {
		mult = 2 << (exp - 1);
	}
	Dictation::setRewindSpeed(mult);
	char label[7];
	if (mult < 10) {
		sprintf(label, "   x%d", mult);
	} else if (mult < 100) {
		sprintf(label, "  x%d", mult);
	} else {
		sprintf(label, " x%d", mult);
	}
	opWin->rewindSpeedLabel->setText(QString(label));
}

void QHandler::fastForwardSpeedSliderChanged(int exp) {
	int mult;
	if (exp == 0) {
		mult = 1;
	} else {
		mult = 2 << (exp - 1);
	}
	Dictation::setFastForwardSpeed(mult);
	char label[7];
	if (mult < 10) {
			sprintf(label, "   x%d", mult);
		} else if (mult < 100) {
			sprintf(label, "  x%d", mult);
		} else {
			sprintf(label, " x%d", mult);
		}
	opWin->fastForwardSpeedLabel->setText(QString(label));
}

void QHandler::slowSpeedSliderChanged(int percent) {
	SLOW_SPEED = ((float) percent) / (float) 100;
	char label[7]; char label2[5];
	sprintf(label, "  %d%%", percent); sprintf(label2, "%d%%", percent);
	opWin->slowSpeedLabel->setText(QString(label));
	opWin->slowSpeedSlider->setValue(percent);
	win->speedLabel->setText(QString(label2));
	win->slowDial->setValue(percent);
	IF_OPEN
	if (D->isSlowed()) D->setSpeed(SLOW_SPEED);
	ENDIF_OPEN
}

void QHandler::closeButtonClicked() {
	optionsWindow->close();
}

/*
 * Qt Footpedal Configuration Window Widget Listeners
 */

void QHandler::footPedalApply() {
	//update the footpedal config file
	FILE *conf = fopen(joystickFile.c_str(), "w");
	char info[258];
	fplModel.getStringID(fpcWin->deviceList->selectionModel()->currentIndex().row(), info);
	if (conf != NULL) {
		if (strcmp(info, "") != 0) {
			fprintf(conf, "%s\n%d\n", &info[2], (unsigned char) info[1]);
			for (unsigned short i = 0; i < (unsigned char) info[1]; i++) fprintf(conf, "%d\n", fpctModel.getCommand(i));
		}
		fclose(conf);
	}
	if (J != NULL) {
		delete J;
		J = NULL;
	}
	joystickCommandLock.lock();
	clearPedalInfo();
	if (strcmp(info, "") != 0) {
		J = new Joystick(info[0] - 1, eventListener);
		for (short i = 0; i < info[1]; i++) pedalCommand[i] = fpctModel.getCommand(i);
	}
	joystickCommandLock.unlock();
	footPedalConfigWindow->close();
}

void QHandler::footPedalCancel() {
	if (!loadFootpedalConfig()) clearPedalInfo();
	footPedalConfigWindow->close();
}

static char *selectedDeviceString;
void QHandler::deviceSelected(const QModelIndex &index, const QModelIndex &prev) {
	fplModel.getStringID(index.row(), selectedDeviceString);
	if (strcmp(selectedDeviceString, "") != 0) {
		fpctModel.changeJoystick(selectedDeviceString[0] - 1, selectedDeviceString[1]);
	} else {
		fpctModel.changeJoystick(0xff, 0);
	}
}

void QHandler::selectionValidCheck(const QModelIndex& dontcare, const QModelIndex& stilldontcare) {
	if (!fplModel.stringIDequals(fpcWin->deviceList->selectionModel()->currentIndex().row() , selectedDeviceString)) {
		notifyJoystickSelectionChanged(QModelIndex());
	}
}

void QHandler::commandChosen(const QModelIndex &index) {
	char msg[33];
	sprintf(msg, "Choose action for footpedal #%d", index.row() + 1);
	fpctModel.changeCommand(index, getCommand(msg, fpctModel.getCommand(index)));
}

//a'right, that's enough listeners!

class MThread : public QThread {
  public:
	MThread() : QThread() {}
  protected:
	void run() {
		unsigned int then = 0xffffffff;
		unsigned int now = 0;
		chrono::milliseconds tick(15);

		while (!windowClosed) {
			dictationLock.lock();
			timeLock.lock();

			if (*SoXError) {
				if (D != NULL) {
					delete D; D = NULL;
					win->fileNameLabel->setText(QString("Nothing"));
					win->positionLabel->setText(QString(" 0:00"));
					win->durationLabel->setText(QString(" 0:00"));
					win->timeSlider->setRange(0, 60000);
				}
				*SoXError = false;
				QMessageBox::critical(root, QString("SoX Error"), QString("An error occurred with the SoX library. Sorry!"));
			}

			if (D != NULL) {
				now = D->getPositionMilliseconds() / 1000;

				if (paused xor D->isPaused()) {
					paused = D->isPaused();
					if (paused) {
						win->playPauseButton->setIcon(playIcon);
					} else {
						win->playPauseButton->setIcon(pauseIcon);
					}
				}
				win->slowButton->setChecked(D->isSlowed());
				win->rewindButton->setChecked(D->isRewinding());
				win->fastForwardButton->setChecked(D->isFastForwarding());

				if (adjustingTimer) {
					unsigned int time = win->timeSlider->sliderPosition() / 1000;
					char ctime[6];
					sprintf(ctime, "%2d:%02d", time / 60, time % 60);
					win->positionLabel->setText(ctime);
					win->positionLabel->update();
				} else {
					if (now != then) {
						char ctime[6];
						sprintf(ctime, "%2d:%02d", now / 60, now % 60);
						win->positionLabel->setText(ctime);
						win->positionLabel->update();
						then = now;
					}

					win->timeSlider->setSliderPosition(D->getPositionMilliseconds());
					win->timeSlider->update();
				}
			}
			timeLock.unlock();
			dictationLock.unlock();

			this_thread::sleep_for(tick);
		}
	}
};

static void doConnectionWait(char *jname) {
	/*
	 * If no joystick is connected when the program starts but there is a
	 * joystick named in the configuration file, keep scanning ports to see if
	 * the joystick becomes connected until either it is found, or the user
	 * opens the joystick configuration window to select one manually
	 */
	chrono::milliseconds ONE_SECOND(1000);
	char otherName[256];
	while (!joystickFound) {
		for (unsigned char i = 0; i <= 9; i++) {
			try {
				Joystick::getNameAndButtons(i, otherName, 256);
			} catch (const invalid_argument &e) {
				continue;
			}
			if (strcmp(otherName, jname) == 0) {
				jsearch.lock();
				if (!joystickFound) J = new Joystick(i, eventListener);
				jsearch.unlock();
				break;
			}
		}
		this_thread::sleep_for(ONE_SECOND);
	}
	//clean up self
	joystickFound = true;
	waitForConnection->detach();
	delete waitForConnection;
}


int main() {
	sox_format_init();
	volatile bool isSoxBroken = false;
	SoXError = &isSoxBroken;

	playIcon.addFile(QString::fromUtf8(":/res/svg/play.svg"));
	pauseIcon.addFile(QString::fromUtf8(":/res/svg/pause.svg"));
	selectedDeviceString = new char[258]; selectedDeviceString[0] = '\0';

	string confDir = getenv("HOME");
	confDir += "/.config/qtranscribe";
	mkdir(confDir.c_str(), S_IRWXU);

	configFile = getenv("HOME");
	configFile += "/.config/qtranscribe/settings.conf";
	joystickFile = getenv("HOME");
	joystickFile += "/.config/qtranscribe/footpedal.conf";

	clearPedalInfo();

	int zero = 0;
	QApplication app(zero, (char **) 0);

	root = new Window();
	win = new Ui::MainWindow();
	win->setupUi(root);
	EXTRAS_SIZE = win->extraStuff->width() + 2;
	win->extraStuff->setVisible(false);
	root->setFixedSize(root->width() - EXTRAS_SIZE, root->height());

	optionsWindow = new OWindow();
	opWin = new Ui::optionsWindow();
	opWin->setupUi(optionsWindow);

	footPedalConfigWindow = new CWindow();
	fpcWin = new Ui::footPedalWindow();
	fpcWin->setupUi(footPedalConfigWindow);
	fpcWin->deviceList->setModel(&fplModel);
	fpcWin->mappingTable->setModel(&fpctModel);
	fpcWin->mappingTable->horizontalHeader()->setResizeMode(QHeaderView::Stretch);

	//main window widget events
	QObject::connect(win->timeSlider, SIGNAL(sliderPressed()), &handler, SLOT(timeSliderPressed()));
	QObject::connect(win->timeSlider, SIGNAL(sliderReleased()), &handler, SLOT(timeSliderReleased()));

	QObject::connect(win->playPauseButton, SIGNAL(clicked()), &handler, SLOT(playPauseButtonClicked()));
	QObject::connect(win->restartButton, SIGNAL(clicked()), &handler, SLOT(restartButtonClicked()));
	QObject::connect(win->back10Button, SIGNAL(clicked()), &handler, SLOT(back10ButtonClicked()));
	QObject::connect(win->back5Button, SIGNAL(clicked()), &handler, SLOT(back5ButtonClicked()));
	QObject::connect(win->slowButton, SIGNAL(clicked()), &handler, SLOT(slowButtonClicked()));
	QObject::connect(win->rewindButton, SIGNAL(pressed()), &handler, SLOT(rewindButtonPressed()));
	QObject::connect(win->rewindButton, SIGNAL(released()), &handler, SLOT(rewindButtonReleased()));
	QObject::connect(win->fastForwardButton, SIGNAL(pressed()), &handler, SLOT(fastForwardButtonPressed()));
	QObject::connect(win->fastForwardButton, SIGNAL(released()), &handler, SLOT(fastForwardButtonReleased()));
	QObject::connect(win->slowDial, SIGNAL(valueChanged(int)), &handler, SLOT(slowSpeedSliderChanged(int)));

	QObject::connect(win->openFileButton, SIGNAL(clicked()), &handler, SLOT(openFileButtonClicked()));
	QObject::connect(win->optionsButtons, SIGNAL(clicked()), &handler, SLOT(optionsButtonClicked()));
	QObject::connect(win->pedalConfigButton, SIGNAL(clicked()), &handler, SLOT(pedalConfigButtonClicked()));
	QObject::connect(win->showExtrasButton, SIGNAL(clicked()), &handler, SLOT(showExtrasButtonClicked()));

	//options window widget events
	QObject::connect(opWin->joystickConfigButton, SIGNAL(clicked()), &handler, SLOT(joystickConfigButtonClicked()));
	QObject::connect(opWin->closeButton, SIGNAL(clicked()), &handler, SLOT(closeButtonClicked()));

	QObject::connect(opWin->soundEffectsCheckbox, SIGNAL(toggled(bool)), &handler, SLOT(soundEffectsCheckboxClicked(bool)));

	QObject::connect(opWin->toggleSkipOnPlay, SIGNAL(toggled(bool)), &handler, SLOT(skipOnPlayCheckboxClicked(bool)));
	QObject::connect(opWin->skipOnPlayDelay, SIGNAL(valueChanged(int)), &handler, SLOT(skipOnPlaySpinnerChanged(int)));

	QObject::connect(opWin->rewindSpeedSlider, SIGNAL(valueChanged(int)), &handler, SLOT(rewindSpeedSliderChanged(int)));
	QObject::connect(opWin->fastForwardSpeedSlider, SIGNAL(valueChanged(int)), &handler, SLOT(fastForwardSpeedSliderChanged(int)));
	QObject::connect(opWin->slowSpeedSlider, SIGNAL(valueChanged(int)), &handler, SLOT(slowSpeedSliderChanged(int)));

	//footpedal config window widget events
	QObject::connect(fpcWin->cancelButton, SIGNAL(clicked()), &handler, SLOT(footPedalCancel()));
	QObject::connect(fpcWin->OkayButton, SIGNAL(clicked()), &handler, SLOT(footPedalApply()));

	QObject::connect(fpcWin->deviceList->selectionModel(), SIGNAL(currentChanged(const QModelIndex&, const QModelIndex&)), &handler, SLOT(deviceSelected(const QModelIndex&, const QModelIndex&)));
	QObject::connect(&fplModel, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), &handler, SLOT(selectionValidCheck(const QModelIndex&, const QModelIndex&)));
	QObject::connect(fpcWin->mappingTable, SIGNAL(activated(const QModelIndex&)), &handler, SLOT(commandChosen(const QModelIndex&)));

	//load options from configuration file
	fstream conf(configFile.c_str(), ios_base::in);
	char *line = new char[256];
	while (conf.good() && !conf.eof()) {
		conf.getline(line, 256, '=');
		trim(line);
		if (strcmp(line, "Playback Skip") == 0) {
			int temp; conf >> temp;
			if (conf.good() && temp <= 0 && temp >= -10000) {
				PLAY_SKIPBACK = temp;
				opWin->toggleSkipOnPlay->setChecked(temp != 0);
				if (temp != 0) opWin->skipOnPlayDelay->setValue(-1 * temp);
			}
		} else if (strcmp(line, "Rewind Speed") == 0) {
			int temp; conf >> temp;
			if (conf.good() && temp >= 1) {
				int v = 0;
				while (temp != 1) {
					v++;
					temp>>=1;
				}
				if (v <= 7) opWin->rewindSpeedSlider->setValue(v);
			}
		} else if (strcmp(line, "Fast Forward Speed") == 0) {
			int temp; conf >> temp;
			if (conf.good() && temp >= 1) {
				int v = 0;
				while (temp != 1) {
					v++;
					temp>>=1;
				}
				if (v <= 7) opWin->fastForwardSpeedSlider->setValue(v);
			}
		} else if (strcmp(line, "Slow Speed") == 0) {
			float temp; conf >> temp;
			if (conf.good() && temp >= 0.2 && temp <= 0.95) {
				SLOW_SPEED = temp;
				opWin->slowSpeedSlider->setValue((int) (100 * temp));
				win->slowDial->setValue((int) (100 * temp));
			}
		} else if (strcmp(line, "Rewind / Fast Forward Sound Effects") == 0) {
			int temp; conf >> temp;
			if (conf.good() && (temp == 0 || temp == 1)) {
				Dictation::setEffectsEnabled((bool) temp);
				opWin->soundEffectsCheckbox->setChecked((bool) temp);
			}
		}
		conf.getline(line, 256, '\n');
	}
	conf.close();
	delete[] line;

	//load footpedal options
	char joyName[257];
	if (loadFootpedalConfig(joyName)) {
		if (J == NULL && joyName[0] != '\0') waitForConnection = new thread(doConnectionWait, joyName);
	} else {
		clearPedalInfo();
		Ui::notConfiguredMessage ncmView;
		QDialog dial;
		ncmView.setupUi(&dial);
		bool saidYes = false;
		if (dial.exec() == QDialog::Accepted) saidYes = true;
		if (ncmView.dontAsk->isChecked()) {
			FILE *joyConf = fopen(joystickFile.c_str(), "w");
			fputc('\n', joyConf);
			fclose(joyConf);
		}
		if (saidYes) footPedalConfigWindow->show();
	}

	root->show();

	MThread *worker = new MThread();
	worker->start();

	app.exec();
	worker->wait();

	app.quit();

	if (J != NULL) delete J;
	if (D != NULL) delete D;

	delete win;
	delete opWin;
	delete fpcWin;
	delete worker;

	delete root;
	delete optionsWindow;
	delete footPedalConfigWindow;

	if (selectedDeviceString != NULL) delete[] selectedDeviceString;

	sox_format_quit();

	return 0;
}