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
crate::ix!();

//-------------------------------------------[.cpp/bitcoin/src/qt/intro.h]

pub const DEFAULT_CHOOSE_DATADIR: bool = false;

/**
  | Introduction screen (pre-GUI startup).
  | 
  | Allows the user to choose a data directory,
  | in which the wallet and block chain will
  | be stored.
  |
  */
#[Q_OBJECT]
pub struct Intro {
    base:                QDialog,
    ui:                  *mut UiIntro,
    thread:              *mut QThread,
    mutex:               QMutex,
    signalled:           bool,
    path_to_check:       String,
    blockchain_size_gb:  i64,
    chain_state_size_gb: i64,

    /**
      | Total required space (in GB) depending
      | on user choice (prune or not prune).
      |
      */
    required_space_gb:   i64, // default = { 0 }

    bytes_available:     u64, // default = { 0 }
    prune_target_gb:     i64,
}

impl Drop for Intro {
    fn drop(&mut self) {
        todo!();
        /*
            delete ui;
        /* Ensure thread is finished before it is deleted */
        thread->quit();
        thread->wait();
        */
    }
}

impl Intro {

    #[Q_SIGNAL]
    pub fn request_check(&mut self)  {
        
        todo!();
        /*
        
        */
    }

    pub fn new(
        parent:              *mut QWidget,
        blockchain_size_gb:  Option<i64>,
        chain_state_size_gb: Option<i64>) -> Self {

        let blockchain_size_gb: i64 =
                 blockchain_size_gb.unwrap_or(0);

        let chain_state_size_gb: i64 =
                 chain_state_size_gb.unwrap_or(0);
    
        todo!();
        /*
           :
        QDialog(parent, typename gui_util::dialog_flags),
        ui(new UiIntro),
        thread(nullptr),
        signalled(false),
        m_blockchain_size_gb(blockchain_size_gb),
        m_chain_state_size_gb(chain_state_size_gb),
        m_prune_target_gb{GetPruneTargetGB()}
        ui->setupUi(this);
        ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(PACKAGE_NAME));
        ui->storageLabel->setText(ui->storageLabel->text().arg(PACKAGE_NAME));

        ui->lblExplanation1->setText(ui->lblExplanation1->text()
            .arg(PACKAGE_NAME)
            .arg(m_blockchain_size_gb)
            .arg(2009)
            .arg(tr("Bitcoin"))
        );
        ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(PACKAGE_NAME));

        const int min_prune_target_GB = std::ceil(MIN_DISK_SPACE_FOR_BLOCK_FILES / 1e9);
        ui->pruneGB->setRange(min_prune_target_GB, std::numeric_limits<int>::max());
        if (gArgs.GetIntArg("-prune", 0) > 1) { // -prune=1 means enabled, above that it's a size in MiB
            ui->prune->setChecked(true);
            ui->prune->setEnabled(false);
        }
        ui->pruneGB->setValue(m_prune_target_gb);
        ui->pruneGB->setToolTip(ui->prune->toolTip());
        ui->lblPruneSuffix->setToolTip(ui->prune->toolTip());
        UpdatePruneLabels(ui->prune->isChecked());

        connect(ui->prune, &QCheckBox::toggled, [this](bool prune_checked) {
            UpdatePruneLabels(prune_checked);
            UpdateFreeSpaceLabel();
        });
        connect(ui->pruneGB, qOverload<int>(&QSpinBox::valueChanged), [this](int prune_GB) {
            m_prune_target_gb = prune_GB;
            UpdatePruneLabels(ui->prune->isChecked());
            UpdateFreeSpaceLabel();
        });

        startThread();
        */
    }
    
    pub fn get_data_directory(&mut self) -> String {
        
        todo!();
        /*
            return ui->dataDirectory->text();
        */
    }
    
    pub fn set_data_directory(&mut self, data_dir: &String)  {
        
        todo!();
        /*
            ui->dataDirectory->setText(dataDir);
        if(dataDir == typename gui_util::getDefaultDataDirectory())
        {
            ui->dataDirDefault->setChecked(true);
            ui->dataDirectory->setEnabled(false);
            ui->ellipsisButton->setEnabled(false);
        } else {
            ui->dataDirCustom->setChecked(true);
            ui->dataDirectory->setEnabled(true);
            ui->ellipsisButton->setEnabled(true);
        }
        */
    }
    
    pub fn get_prune_mib(&self) -> i64 {
        
        todo!();
        /*
            switch (ui->prune->checkState()) {
        case QtChecked:
            return PruneGBtoMiB(m_prune_target_gb);
        case QtUnchecked: default:
            return 0;
        }
        */
    }
    
    /**
      | Determine data directory. Let the user
      | choose if the current one doesn't exist.
      | 
      | Let the user configure additional preferences
      | such as pruning.
      | 
      | -----------
      | @note
      | 
      | do NOT call global gArgs.GetDataDirNet()
      | before calling this function, this
      | will cause the wrong path to be cached.
      | 
      | -----------
      | @return
      | 
      | true if a data directory was selected,
      | false if the user cancelled the selection
      | dialog.
      |
      */
    pub fn show_if_needed(&mut self, 
        did_show_intro: &mut bool,
        prune_mib:      &mut i64) -> bool {
        
        todo!();
        /*
            did_show_intro = false;

        QSettings settings;
        /* If data directory provided on command line, no need to look at settings
           or show a picking dialog */
        if(!gArgs.GetArg("-datadir", "").empty())
            return true;
        /* 1) Default data directory for operating system */
        QString dataDir = typename gui_util::getDefaultDataDirectory();
        /* 2) Allow QSettings to override default dir */
        dataDir = settings.value("strDataDir", dataDir).toString();

        if(!fs::exists(typename gui_util::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg("-choosedatadir", DEFAULT_CHOOSE_DATADIR) || settings.value("fReset", false).toBool() || gArgs.GetBoolArg("-resetguisettings", false))
        {
            /* Use selectParams here to guarantee Params() can be used by node interface */
            try {
                SelectParams(gArgs.GetChainName());
            } catch (const std::exception&) {
                return false;
            }

            /* If current default data directory does not exist, let the user choose one */
            Intro intro(0, Params().AssumedBlockchainSize(), Params().AssumedChainStateSize());
            intro.setDataDirectory(dataDir);
            intro.setWindowIcon(QIcon(":icons/bitcoin"));
            did_show_intro = true;

            while(true)
            {
                if(!intro.exec())
                {
                    /* Cancel clicked */
                    return false;
                }
                dataDir = intro.getDataDirectory();
                try {
                    if (TryCreateDirectories(typename gui_util::qstringToBoostPath(dataDir))) {
                        // If a new data directory has been created, make wallets subdirectory too
                        TryCreateDirectories(typename gui_util::qstringToBoostPath(dataDir) / "wallets");
                    }
                    break;
                } catch (const fs::filesystem_error&) {
                    QMessageBox::critical(nullptr, PACKAGE_NAME,
                        tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir));
                    /* fall through, back to choosing screen */
                }
            }

            // Additional preferences:
            prune_MiB = intro.getPruneMiB();

            settings.setValue("strDataDir", dataDir);
            settings.setValue("fReset", false);
        }
        /* Only override -datadir if different from the default, to make it possible to
         * override -datadir in the bitcoin.conf file in the default data directory
         * (to be consistent with bitcoind behavior)
         */
        if(dataDir != typename gui_util::getDefaultDataDirectory()) {
            gArgs.SoftSetArg("-datadir", fs::PathToString(typename gui_util::qstringToBoostPath(dataDir))); // use OS locale for path setting
        }
        return true;
        */
    }
    
    #[Q_SLOT]
    pub fn set_status(&mut self, 
        status:          i32,
        message:         &String,
        bytes_available: u64)  {
        
        todo!();
        /*
            switch(status)
        {
        case FreespaceChecker::ST_OK:
            ui->errorMessage->setText(message);
            ui->errorMessage->setStyleSheet("");
            break;
        case FreespaceChecker::ST_ERROR:
            ui->errorMessage->setText(tr("Error") + ": " + message);
            ui->errorMessage->setStyleSheet("QLabel { color: #800000 }");
            break;
        }
        /* Indicate number of bytes available */
        if(status == FreespaceChecker::ST_ERROR)
        {
            ui->freeSpace->setText("");
        } else {
            m_bytes_available = bytesAvailable;
            if (ui->prune->isEnabled()) {
                ui->prune->setChecked(m_bytes_available < (m_blockchain_size_gb + m_chain_state_size_gb + 10) * GB_BYTES);
            }
            UpdateFreeSpaceLabel();
        }
        /* Don't allow confirm in ERROR state */
        ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);
        */
    }
    
    pub fn update_free_space_label(&mut self)  {
        
        todo!();
        /*
            QString freeString = tr("%1 GB of free space available").arg(m_bytes_available / GB_BYTES);
        if (m_bytes_available < m_required_space_gb * GB_BYTES) {
            freeString += " " + tr("(of %1 GB needed)").arg(m_required_space_gb);
            ui->freeSpace->setStyleSheet("QLabel { color: #800000 }");
        } else if (m_bytes_available / GB_BYTES - m_required_space_gb < 10) {
            freeString += " " + tr("(%1 GB needed for full chain)").arg(m_required_space_gb);
            ui->freeSpace->setStyleSheet("QLabel { color: #999900 }");
        } else {
            ui->freeSpace->setStyleSheet("");
        }
        ui->freeSpace->setText(freeString + ".");
        */
    }
    
    #[Q_SLOT]
    pub fn on_data_directory_text_changed(&mut self, data_dir_str: &String)  {
        
        todo!();
        /*
            /* Disable OK button until check result comes in */
        ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
        checkPath(dataDirStr);
        */
    }
    
    pub fn on_ellipsis_button_clicked(&mut self)  {
        
        todo!();
        /*
            QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(nullptr, "Choose data directory", ui->dataDirectory->text()));
        if(!dir.isEmpty())
            ui->dataDirectory->setText(dir);
        */
    }
    
    pub fn on_data_dir_default_clicked(&mut self)  {
        
        todo!();
        /*
            setDataDirectory(typename gui_util::getDefaultDataDirectory());
        */
    }
    
    pub fn on_data_dir_custom_clicked(&mut self)  {
        
        todo!();
        /*
            ui->dataDirectory->setEnabled(true);
        ui->ellipsisButton->setEnabled(true);
        */
    }
    
    pub fn start_thread(&mut self)  {
        
        todo!();
        /*
            thread = new QThread(this);
        FreespaceChecker *executor = new FreespaceChecker(this);
        executor->moveToThread(thread);

        connect(executor, &FreespaceChecker::reply, this, &Intro::setStatus);
        connect(this, &Intro::requestCheck, executor, &FreespaceChecker::check);
        /*  make sure executor object is deleted in its own thread */
        connect(thread, &QThread::finished, executor, &QObject::deleteLater);

        thread->start();
        */
    }
    
    pub fn check_path(&mut self, data_dir: &String)  {
        
        todo!();
        /*
            mutex.lock();
        pathToCheck = dataDir;
        if(!signalled)
        {
            signalled = true;
            Q_EMIT requestCheck();
        }
        mutex.unlock();
        */
    }
    
    pub fn get_path_to_check(&mut self) -> String {
        
        todo!();
        /*
            QString retval;
        mutex.lock();
        retval = pathToCheck;
        signalled = false; /* new request can be queued now */
        mutex.unlock();
        return retval;
        */
    }
    
    pub fn update_prune_labels(&mut self, prune_checked: bool)  {
        
        todo!();
        /*
            m_required_space_gb = m_blockchain_size_gb + m_chain_state_size_gb;
        QString storageRequiresMsg = tr("At least %1 GB of data will be stored in this directory, and it will grow over time.");
        if (prune_checked && m_prune_target_gb <= m_blockchain_size_gb) {
            m_required_space_gb = m_prune_target_gb + m_chain_state_size_gb;
            storageRequiresMsg = tr("Approximately %1 GB of data will be stored in this directory.");
        }
        ui->lblExplanation3->setVisible(prune_checked);
        ui->pruneGB->setEnabled(prune_checked);
        static constexpr uint64_t nPowTargetSpacing = 10 * 60;  // from chainparams, which we don't have at this stage
        static constexpr uint32_t expected_block_data_size = 2250000;  // includes undo data
        const uint64_t expected_backup_days = m_prune_target_gb * 1e9 / (uint64_t(expected_block_data_size) * 86400 / nPowTargetSpacing);
        ui->lblPruneSuffix->setText(
            //: Explanatory text on the capability of the current prune target.
            tr("(sufficient to restore backups %n day(s) old)", "", expected_backup_days));
        ui->sizeWarningLabel->setText(
            tr("%1 will download and store a copy of the Bitcoin block chain.").arg(PACKAGE_NAME) + " " +
            storageRequiresMsg.arg(m_required_space_gb) + " " +
            tr("The wallet will also be stored in this directory.")
        );
        this->adjustSize();
        */
    }
}

//-------------------------------------------[.cpp/bitcoin/src/qt/intro.cpp]

/**
  | Check free space asynchronously to
  | prevent hanging the UI thread.
  | 
  | Up to one request to check a path is in
  | flight to this thread; when the check()
  | function runs, the current path is requested
  | from the associated Intro object.
  | 
  | The reply is sent back through a signal.
  | 
  | This ensures that no queue of checking
  | requests is built up while the user is
  | still entering the path, and that always
  | the most recently entered path is checked
  | as soon as the thread becomes available.
  |
  */
#[Q_OBJECT]
pub struct FreespaceChecker {
    base:  QObject,
    intro: *mut Intro,
}

pub enum FreespaceCheckerStatus {
    ST_OK,
    ST_ERROR
}

impl FreespaceChecker {
    
    #[Q_SIGNAL]
    pub fn reply(&mut self, 
        status:    i32,
        message:   &String,
        available: u64)  {
        
        todo!();
        /*
        
        */
    }
    
    pub fn new(intro: *mut Intro) -> Self {
    
        todo!();
        /*
            this->intro = _intro;
        */
    }
    
    #[Q_SLOT]
    pub fn check(&mut self)  {
        
        todo!();
        /*
            QString dataDirStr = intro->getPathToCheck();
        fs::path dataDir = typename gui_util::qstringToBoostPath(dataDirStr);
        uint64_t freeBytesAvailable = 0;
        int replyStatus = ST_OK;
        QString replyMessage = tr("A new data directory will be created.");

        /* Find first parent that exists, so that fs::space does not fail */
        fs::path parentDir = dataDir;
        fs::path parentDirOld = fs::path();
        while(parentDir.has_parent_path() && !fs::exists(parentDir))
        {
            parentDir = parentDir.parent_path();

            /* Check if we make any progress, break if not to prevent an infinite loop here */
            if (parentDirOld == parentDir)
                break;

            parentDirOld = parentDir;
        }

        try {
            freeBytesAvailable = fs::space(parentDir).available;
            if(fs::exists(dataDir))
            {
                if(fs::is_directory(dataDir))
                {
                    QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>";
                    replyStatus = ST_OK;
                    replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator);
                } else {
                    replyStatus = ST_ERROR;
                    replyMessage = tr("Path already exists, and is not a directory.");
                }
            }
        } catch (const fs::filesystem_error&)
        {
            /* Parent directory does not exist or is not accessible */
            replyStatus = ST_ERROR;
            replyMessage = tr("Cannot create data directory here.");
        }
        Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable);
        */
    }
}

/**
  | Return pruning size that will be used
  | if automatic pruning is enabled.
  |
  */
pub fn get_prune_targetgb() -> i32 {
    
    todo!();
        /*
            int64_t prune_target_mib = gArgs.GetIntArg("-prune", 0);
        // >1 means automatic pruning is enabled by config, 1 means manual pruning, 0 means no pruning.
        return prune_target_mib > 1 ? PruneMiBtoGB(prune_target_mib) : DEFAULT_PRUNE_TARGET_GB;
        */
}