summaryrefslogtreecommitdiffhomepage
path: root/proto-ft/mutex.cpp
blob: 63cf433413647dfd0c45c67bcd3ebce221ace3c5 (plain)
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
#include "ftnoir_protocol_ft.h"
#include "mutex.hpp"
#include <windows.h>
#include <QDebug>

check_for_first_run::check_for_first_run() : checked_for_first_run(false), is_first_instance(false), enabled(false)
{
}

bool check_for_first_run::is_first_run()
{
    return checked_for_first_run && is_first_instance;
}

void check_for_first_run::set_enabled(bool flag)
{
    enabled = flag;
    qDebug() << "ft runonce:" << "enabled" << flag;
}

void check_for_first_run::try_runonce()
{
    constexpr const char* name = "opentrack-freetrack-runonce";
    
    if (checked_for_first_run)
        return;
    
    // just leak it, no issue
    HANDLE h = CreateMutexA(nullptr, false, name);
    
    switch (WaitForSingleObject(h, 0))
    {
    case WAIT_OBJECT_0:
        is_first_instance = true;
        checked_for_first_run = true;
        break;
    case WAIT_TIMEOUT:
        checked_for_first_run = true;
        break;
    default:
        checked_for_first_run = false;
        break;
    }
    
    if (checked_for_first_run && !is_first_instance)
        CloseHandle(h);
    
    qDebug() << "ft runonce:" << "enabled" << enabled << "first-run" << is_first_instance << "checked" << checked_for_first_run;
}

check_for_first_run::~check_for_first_run()
{
    try_exit();
}

void check_for_first_run::try_exit()
{
    qDebug() << "ft runonce enabled:" << enabled;
    if (is_first_instance && enabled)
    {
        qDebug() << "ft runonce: removing registry keys";
        FTNoIR_Protocol::set_protocols(false, false);
    }
}