File: jucer_CompileEngineClient.cpp

package info (click to toggle)
juce 5.4.1%2Breally5.4.1~repack-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 45,904 kB
  • sloc: cpp: 359,333; java: 15,402; ansic: 750; xml: 243; sh: 192; makefile: 146; cs: 132; python: 117
file content (911 lines) | stat: -rw-r--r-- 28,030 bytes parent folder | download | duplicates (2)
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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

#include "../Application/jucer_Headers.h"
#include "../Application/jucer_Application.h"
#include "../ProjectSaving/jucer_ProjectExporter.h"
#include "jucer_MessageIDs.h"
#include "jucer_CppHelpers.h"
#include "jucer_SourceCodeRange.h"
#include "jucer_ClassDatabase.h"
#include "jucer_DiagnosticMessage.h"
#include "jucer_ProjectBuildInfo.h"
#include "jucer_ClientServerMessages.h"
#include "jucer_CompileEngineClient.h"
#include "jucer_CompileEngineServer.h"
#include "jucer_CompileEngineSettings.h"

#ifndef RUN_CLANG_IN_CHILD_PROCESS
 #error
#endif

//==============================================================================
static File getProjucerTempFolder() noexcept
{
   #if JUCE_MAC
    return { "~/Library/Caches/com.juce.projucer" };
   #else
    return File::getSpecialLocation (File::tempDirectory).getChildFile ("com.juce.projucer");
   #endif
}

static File getCacheLocationForProject (Project& project) noexcept
{
    auto cacheFolderName = project.getProjectFilenameRootString() + "_" + project.getProjectUIDString();

   #if JUCE_DEBUG
    cacheFolderName += "_debug";
   #endif

    return getProjucerTempFolder().getChildFile ("Intermediate Files").getChildFile (cacheFolderName);
}

//==============================================================================
class ClientIPC  : public MessageHandler,
                   private InterprocessConnection,
                   private Timer
{
public:
    ClientIPC (CompileEngineChildProcess& cp)
       : InterprocessConnection (true), owner (cp)
    {
        launchServer();
    }

    ~ClientIPC()
    {
       #if RUN_CLANG_IN_CHILD_PROCESS
        if (childProcess.isRunning())
        {
           #if JUCE_DEBUG
            killServerPolitely();
           #else
            // in release builds we don't want to wait
            // for the server to clean up and shut down
            killServerWithoutMercy();
           #endif
        }
       #endif
    }

    void launchServer()
    {
        DBG ("Client: Launching Server...");

        auto pipeName = "ipc_" + String::toHexString (Random().nextInt64());
        auto command = createCommandLineForLaunchingServer (pipeName, owner.project.getProjectUIDString(),
                                                            getCacheLocationForProject (owner.project));

       #if RUN_CLANG_IN_CHILD_PROCESS
        if (! childProcess.start (command))
            jassertfalse;
       #else
        server = createClangServer (command);
       #endif

        for (int i = 0; i < 20; ++i)
        {
            if (connectToPipe (pipeName, 10000))
            {
                MessageTypes::sendPing (*this);
                break;
            }

            Thread::sleep (50);
        }

        jassert (isConnected());

        startTimer (serverKeepAliveTimeout);
    }

    void killServerPolitely()
    {
        DBG ("Client: Killing Server...");
        MessageTypes::sendQuit (*this);

        disconnect();
        stopTimer();

       #if RUN_CLANG_IN_CHILD_PROCESS
        childProcess.waitForProcessToFinish (5000);
       #endif

        killServerWithoutMercy();
    }

    void killServerWithoutMercy()
    {
        disconnect();
        stopTimer();

       #if RUN_CLANG_IN_CHILD_PROCESS
        childProcess.kill();
       #else
        destroyClangServer (server);
        server = nullptr;
       #endif
    }

    void connectionMade()
    {
        DBG ("Client: connected");
        stopTimer();
    }

    void connectionLost()
    {
        DBG ("Client: disconnected");
        startTimer (100);
    }

    bool sendMessage (const ValueTree& m)
    {
        return InterprocessConnection::sendMessage (MessageHandler::convertMessage (m));
    }

    void messageReceived (const MemoryBlock& message)
    {
       #if RUN_CLANG_IN_CHILD_PROCESS
        startTimer (serverKeepAliveTimeout);
       #else
        stopTimer();
       #endif
        MessageTypes::dispatchToClient (owner, MessageHandler::convertMessage (message));
    }

    enum { serverKeepAliveTimeout = 10000 };

private:
    CompileEngineChildProcess& owner;

   #if RUN_CLANG_IN_CHILD_PROCESS
    ChildProcess childProcess;
   #else
    void* server;
   #endif

    void timerCallback()
    {
        stopTimer();
        owner.handleCrash (String());
    }
};

//==============================================================================
class CompileEngineChildProcess::ChildProcess    : private ValueTree::Listener,
                                                   private Timer
{
public:
    ChildProcess (CompileEngineChildProcess& proc, Project& p)
        : owner (proc), project (p)
    {
        projectRoot = project.getProjectRoot();

        restartServer();
        projectRoot.addListener (this);
        openedOk = true;
    }

    ~ChildProcess()
    {
        projectRoot.removeListener (this);

        if (isRunningApp && server != nullptr)
            server->killServerWithoutMercy();

        server.reset();
    }

    void restartServer()
    {
        server.reset (new ClientIPC (owner));
        sendRebuild();
    }

    void sendRebuild()
    {
        stopTimer();

        ProjectBuildInfo build;

        if (! doesProjectMatchSavedHeaderState (project))
        {
            MessageTypes::sendNewBuild (*server, build);

            owner.errorList.resetToError ("Project structure does not match the saved headers! "
                                          "Please re-save your project to enable compilation");
            return;
        }

        if (areAnyModulesMissing (project))
        {
            MessageTypes::sendNewBuild (*server, build);

            owner.errorList.resetToError ("Some of your JUCE modules can't be found! "
                                          "Please check that all the module paths are correct");
            return;
        }

        build.setSystemIncludes (getSystemIncludePaths());
        build.setUserIncludes (getUserIncludes());

        build.setGlobalDefs (getGlobalDefs());
        build.setCompileFlags (project.getCompileEngineSettings().getExtraCompilerFlagsString());
        build.setExtraDLLs (getExtraDLLs());
        build.setJuceModulesFolder (EnabledModuleList::findDefaultModulesFolder (project).getFullPathName());

        build.setUtilsCppInclude (project.getAppIncludeFile().getFullPathName());

        build.setWindowsTargetPlatformVersion (project.getCompileEngineSettings().getWindowsTargetPlatformVersionString());

        scanForProjectFiles (project, build);

        owner.updateAllEditors();

        MessageTypes::sendNewBuild (*server, build);
    }

    void cleanAll()
    {
        MessageTypes::sendCleanAll (*server);
        sendRebuild();
    }

    void reinstantiatePreviews()
    {
        MessageTypes::sendReinstantiate (*server);
    }

    bool launchApp()
    {
        MessageTypes::sendLaunchApp (*server);
        return true;
    }

    std::unique_ptr<ClientIPC> server;

    bool openedOk = false;
    bool isRunningApp = false;

private:
    CompileEngineChildProcess& owner;
    Project& project;
    ValueTree projectRoot;

    void projectStructureChanged()
    {
        startTimer (100);
    }

    void timerCallback() override
    {
        sendRebuild();
    }

    void valueTreePropertyChanged (ValueTree&, const Identifier&) override       { projectStructureChanged(); }
    void valueTreeChildAdded (ValueTree&, ValueTree&) override                   { projectStructureChanged(); }
    void valueTreeChildRemoved (ValueTree&, ValueTree&, int) override            { projectStructureChanged(); }
    void valueTreeParentChanged (ValueTree&) override                            { projectStructureChanged(); }
    void valueTreeChildOrderChanged (ValueTree&, int, int) override              {}

    String getGlobalDefs()
    {
        StringArray defs;

        defs.add (project.getCompileEngineSettings().getExtraPreprocessorDefsString());

        {
            auto projectDefines = project.getPreprocessorDefs();

            for (int i = 0; i < projectDefines.size(); ++i)
            {
                auto def = projectDefines.getAllKeys()[i];
                auto value = projectDefines.getAllValues()[i];

                if (value.isNotEmpty())
                    def << "=" << value;

                 defs.add (def);
            }
        }

        for (Project::ExporterIterator exporter (project); exporter.next();)
            if (exporter->canLaunchProject())
                defs.add (exporter->getExporterIdentifierMacro() + "=1");

        // Use the JUCE implementation of std::function until the live build
        // engine can compile the one from the standard library
        defs.add (" _LIBCPP_FUNCTIONAL=1");
        defs.removeEmptyStrings();

        return defs.joinIntoString (" ");
    }

    static void scanProjectItem (const Project::Item& projectItem, Array<File>& compileUnits, Array<File>& userFiles)
    {
        if (projectItem.isGroup())
        {
            for (int i = 0; i < projectItem.getNumChildren(); ++i)
                scanProjectItem (projectItem.getChild(i), compileUnits, userFiles);

            return;
        }

        if (projectItem.shouldBeCompiled())
        {
            auto f = projectItem.getFile();

            if (f.exists())
                compileUnits.add (f);
        }

        if (projectItem.shouldBeAddedToTargetProject() && ! projectItem.shouldBeAddedToBinaryResources())
        {
            auto f = projectItem.getFile();

            if (f.exists())
                userFiles.add (f);
        }
    }

    void scanForProjectFiles (Project& proj, ProjectBuildInfo& build)
    {
        Array<File> compileUnits, userFiles;
        scanProjectItem (proj.getMainGroup(), compileUnits, userFiles);

        {
            auto isVSTHost = project.getEnabledModules().isModuleEnabled ("juce_audio_processors")
                   && (project.isConfigFlagEnabled ("JUCE_PLUGINHOST_VST3") || project.isConfigFlagEnabled ("JUCE_PLUGINHOST_VST"));

            auto isPluginProject = proj.getProjectType().isAudioPlugin();

            OwnedArray<LibraryModule> modules;
            proj.getEnabledModules().createRequiredModules (modules);

            for (Project::ExporterIterator exporter (proj); exporter.next();)
            {
                if (exporter->canLaunchProject())
                {
                    for (auto* m : modules)
                    {
                        auto localModuleFolder = proj.getEnabledModules().shouldCopyModuleFilesLocally (m->moduleInfo.getID()).getValue()
                                                        ? proj.getLocalModuleFolder (m->moduleInfo.getID())
                                                        : m->moduleInfo.getFolder();


                        m->findAndAddCompiledUnits (*exporter, nullptr, compileUnits,
                                                    isPluginProject || isVSTHost ? ProjectType::Target::SharedCodeTarget
                                                                                 : ProjectType::Target::unspecified);

                        if (isPluginProject || isVSTHost)
                            m->findAndAddCompiledUnits (*exporter, nullptr, compileUnits, ProjectType::Target::StandalonePlugIn);
                    }

                    break;
                }
            }
        }

        for (int i = 0; ; ++i)
        {
            auto binaryDataCpp = proj.getBinaryDataCppFile (i);
            if (! binaryDataCpp.exists())
                break;

            compileUnits.add (binaryDataCpp);
        }

        for (auto i = compileUnits.size(); --i >= 0;)
            if (compileUnits.getReference(i).hasFileExtension (".r"))
                compileUnits.remove (i);

        build.setFiles (compileUnits, userFiles);
    }

    static bool doesProjectMatchSavedHeaderState (Project& project)
    {
        auto liveModules = project.getProjectRoot().getChildWithName (Ids::MODULES);

        auto xml = parseXML (project.getFile());

        if (xml == nullptr || ! xml->hasTagName (Ids::JUCERPROJECT.toString()))
            return false;

        auto diskModules = ValueTree::fromXml (*xml).getChildWithName (Ids::MODULES);

        return liveModules.isEquivalentTo (diskModules);
    }

    static bool areAnyModulesMissing (Project& project)
    {
        OwnedArray<LibraryModule> modules;
        project.getEnabledModules().createRequiredModules (modules);

        for (auto* module : modules)
            if (! module->getFolder().isDirectory())
                return true;

        return false;
    }

    StringArray getUserIncludes()
    {
        StringArray paths;
        paths.add (project.getGeneratedCodeFolder().getFullPathName());
        paths.addArray (getSearchPathsFromString (project.getCompileEngineSettings().getUserHeaderPathString()));

        return convertSearchPathsToAbsolute (paths);
    }

    StringArray getSystemIncludePaths()
    {
        StringArray paths;
        paths.addArray (getSearchPathsFromString (project.getCompileEngineSettings().getSystemHeaderPathString()));

        auto isVSTHost = project.getEnabledModules().isModuleEnabled ("juce_audio_processors")
                       && (project.isConfigFlagEnabled ("JUCE_PLUGINHOST_VST3")
                             || project.isConfigFlagEnabled ("JUCE_PLUGINHOST_VST"));

        auto customVst3Path = getAppSettings().getStoredPath (Ids::vst3Path, TargetOS::getThisOS()).get().toString();

        if (customVst3Path.isNotEmpty() && (project.getProjectType().isAudioPlugin() || isVSTHost))
            paths.add (customVst3Path);

        OwnedArray<LibraryModule> modules;
        project.getEnabledModules().createRequiredModules (modules);

        for (auto* module : modules)
        {
            paths.addIfNotAlreadyThere (module->getFolder().getParentDirectory().getFullPathName());

            if (customVst3Path.isEmpty() && (project.getProjectType().isAudioPlugin() || isVSTHost))
                if (module->getID() == "juce_audio_processors")
                    paths.addIfNotAlreadyThere (module->getFolder().getChildFile ("format_types").getChildFile ("VST3_SDK").getFullPathName());
        }

        return convertSearchPathsToAbsolute (paths);
    }

    StringArray convertSearchPathsToAbsolute (const StringArray& paths) const
    {
        StringArray s;
        const File root (project.getProjectFolder());

        for (String p : paths)
            s.add (root.getChildFile (p).getFullPathName());

        return s;
    }

    StringArray getExtraDLLs()
    {
        auto dlls = StringArray::fromTokens (project.getCompileEngineSettings().getExtraDLLsString(), "\n\r,", {});
        dlls.trim();
        dlls.removeEmptyStrings();

        return dlls;
    }

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChildProcess)
};

//==============================================================================
CompileEngineChildProcess::CompileEngineChildProcess (Project& p)
    : project (p)
{
    ProjucerApplication::getApp().openDocumentManager.addListener (this);
    createProcess();
    errorList.setWarningsEnabled (project.getCompileEngineSettings().areWarningsEnabled());
}

CompileEngineChildProcess::~CompileEngineChildProcess()
{
    ProjucerApplication::getApp().openDocumentManager.removeListener (this);

    process.reset();
    lastComponentList.clear();
}

void CompileEngineChildProcess::createProcess()
{
    jassert (process == nullptr);
    process.reset (new ChildProcess (*this, project));

    if (! process->openedOk)
        process.reset();

    updateAllEditors();
}

void CompileEngineChildProcess::cleanAll()
{
    if (process != nullptr)
        process->cleanAll();
}

void CompileEngineChildProcess::openPreview (const ClassDatabase::Class& comp)
{
    if (process != nullptr)
    {
        MainWindow* projectWindow = nullptr;
        OwnedArray<MainWindow>& windows = ProjucerApplication::getApp().mainWindowList.windows;

        for (int i = 0; i < windows.size(); ++i)
        {
            if (MainWindow* w = windows[i])
            {
                if (w->getProject() == &project)
                {
                    projectWindow = w;
                    break;
                }
            }
        }

        Rectangle<int> mainWindowRect;

        if (projectWindow != nullptr)
            mainWindowRect = projectWindow->getBounds();

        MessageTypes::sendOpenPreview (*process->server, comp, mainWindowRect);
    }
}

void CompileEngineChildProcess::reinstantiatePreviews()
{
    if (process != nullptr)
        process->reinstantiatePreviews();
}

void CompileEngineChildProcess::processActivationChanged (bool isForeground)
{
    if (process != nullptr)
        MessageTypes::sendProcessActivationState (*process->server, isForeground);
}

//==============================================================================
bool CompileEngineChildProcess::canLaunchApp() const
{
    return process != nullptr
            && runningAppProcess == nullptr
            && activityList.getNumActivities() == 0
            && errorList.getNumErrors() == 0
            && project.getProjectType().isGUIApplication();
}

void CompileEngineChildProcess::launchApp()
{
    if (process != nullptr)
        process->launchApp();
}

bool CompileEngineChildProcess::canKillApp() const
{
    return runningAppProcess != nullptr;
}

void CompileEngineChildProcess::killApp()
{
    runningAppProcess.reset();
}

void CompileEngineChildProcess::handleAppLaunched()
{
    runningAppProcess.reset (process.release());
    runningAppProcess->isRunningApp = true;
    createProcess();
}

void CompileEngineChildProcess::handleAppQuit()
{
    DBG ("handleAppQuit");
    runningAppProcess.reset();
}

bool CompileEngineChildProcess::isAppRunning() const noexcept
{
    return runningAppProcess != nullptr && runningAppProcess->isRunningApp;
}

//==============================================================================
struct CompileEngineChildProcess::Editor  : private CodeDocument::Listener,
                                            private Timer
{
    Editor (CompileEngineChildProcess& ccp, const File& f, CodeDocument& doc)
        : owner (ccp), file (f), document (doc), transactionTimer (doc)
    {
        sendFullUpdate();
        document.addListener (this);
    }

    ~Editor()
    {
        document.removeListener (this);
    }

    void codeDocumentTextInserted (const String& newText, int insertIndex) override
    {
        CodeChange (Range<int> (insertIndex, insertIndex), newText).addToList (pendingChanges);
        startEditorChangeTimer();
        transactionTimer.stopTimer();

        owner.lastComponentList.globalNamespace
           .nudgeAllCodeRanges (file.getFullPathName(), insertIndex, newText.length());
    }

    void codeDocumentTextDeleted (int start, int end) override
    {
        CodeChange (Range<int> (start, end), String()).addToList (pendingChanges);
        startEditorChangeTimer();
        transactionTimer.stopTimer();

        owner.lastComponentList.globalNamespace
           .nudgeAllCodeRanges (file.getFullPathName(), start, start - end);
    }

    void sendFullUpdate()
    {
        reset();

        if (owner.process != nullptr)
            MessageTypes::sendFileContentFullUpdate (*owner.process->server, file, document.getAllContent());
    }

    bool flushEditorChanges()
    {
        if (pendingChanges.size() > 0)
        {
            if (owner.process != nullptr && owner.process->server != nullptr)
                MessageTypes::sendFileChanges (*owner.process->server, pendingChanges, file);

            reset();
            return true;
        }

        stopTimer();
        return false;
    }

    void reset()
    {
        stopTimer();
        pendingChanges.clear();
    }

    void startTransactionTimer()
    {
        transactionTimer.startTimer (1000);
    }

    void startEditorChangeTimer()
    {
        startTimer (200);
    }

    CompileEngineChildProcess& owner;
    File file;
    CodeDocument& document;

private:
    Array<CodeChange> pendingChanges;

    void timerCallback() override
    {
        if (owner.project.getCompileEngineSettings().isContinuousRebuildEnabled())
            flushEditorChanges();
        else
            stopTimer();
    }

    struct TransactionTimer   : public Timer
    {
        TransactionTimer (CodeDocument& doc) : document (doc) {}

        void timerCallback() override
        {
            stopTimer();
            document.newTransaction();
        }

        CodeDocument& document;
    };

    TransactionTimer transactionTimer;
};

void CompileEngineChildProcess::editorOpened (const File& file, CodeDocument& document)
{
    editors.add (new Editor (*this, file, document));
}

bool CompileEngineChildProcess::documentAboutToClose (OpenDocumentManager::Document* document)
{
    for (int i = editors.size(); --i >= 0;)
    {
        if (document->getFile() == editors.getUnchecked(i)->file)
        {
            const File f (editors.getUnchecked(i)->file);
            editors.remove (i);

            if (process != nullptr)
                MessageTypes::sendHandleFileReset (*process->server, f);
        }
    }

    return true;
}

void CompileEngineChildProcess::updateAllEditors()
{
    for (int i = editors.size(); --i >= 0;)
        editors.getUnchecked(i)->sendFullUpdate();
}

//==============================================================================
void CompileEngineChildProcess::handleCrash (const String& message)
{
    Logger::writeToLog ("*** Child process crashed: " + message);

    if (crashHandler != nullptr)
        crashHandler (message);
}

void CompileEngineChildProcess::handleNewDiagnosticList (const ValueTree& l)         { errorList.setList (l); }
void CompileEngineChildProcess::handleActivityListChanged (const StringArray& l)     { activityList.setList (l); }

void CompileEngineChildProcess::handleCloseIDE()
{
    if (JUCEApplication* app = JUCEApplication::getInstance())
        app->systemRequestedQuit();
}

void CompileEngineChildProcess::handleMissingSystemHeaders()
{
    if (ProjectContentComponent* p = findProjectContentComponent())
        p->handleMissingSystemHeaders();
}

void CompileEngineChildProcess::handleKeyPress (const String& className, const KeyPress& key)
{
    ApplicationCommandManager& commandManager = ProjucerApplication::getCommandManager();

    CommandID command = commandManager.getKeyMappings()->findCommandForKeyPress (key);

    if (command == StandardApplicationCommandIDs::undo)
    {
        handleUndoInEditor (className);
    }
    else if (command == StandardApplicationCommandIDs::redo)
    {
        handleRedoInEditor (className);
    }
    else if (ApplicationCommandTarget* const target = ApplicationCommandManager::findTargetForComponent (findProjectContentComponent()))
    {
        commandManager.setFirstCommandTarget (target);
        commandManager.getKeyMappings()->keyPressed (key, findProjectContentComponent());
        commandManager.setFirstCommandTarget (nullptr);
    }
}

void CompileEngineChildProcess::handleUndoInEditor (const String& /*className*/)
{
}

void CompileEngineChildProcess::handleRedoInEditor (const String& /*className*/)
{
}

void CompileEngineChildProcess::handleClassListChanged (const ValueTree& newList)
{
    lastComponentList = ClassDatabase::ClassList::fromValueTree (newList);
    activityList.sendClassListChangedMessage (lastComponentList);
}

void CompileEngineChildProcess::handleBuildFailed()
{
    ProjucerApplication::getCommandManager().commandStatusChanged();
}

void CompileEngineChildProcess::handleChangeCode (const SourceCodeRange& location, const String& newText)
{
    if (Editor* ed = getOrOpenEditorFor (location.file))
    {
        if (ed->flushEditorChanges())
            return; // client-side editor changes were pending, so deal with them first, and discard
                    // the incoming change, whose position may now be wrong.

        ed->document.deleteSection (location.range.getStart(), location.range.getEnd());
        ed->document.insertText (location.range.getStart(), newText);

        // deliberately clear the messages that we just added, to avoid these changes being
        // sent to the server (which will already have processed the same ones locally)
        ed->reset();
        ed->startTransactionTimer();
    }
}

void CompileEngineChildProcess::handlePing()
{
}

//==============================================================================
void CompileEngineChildProcess::flushEditorChanges()
{
    for (Editor* ed : editors)
        ed->flushEditorChanges();
}

ProjectContentComponent* CompileEngineChildProcess::findProjectContentComponent() const
{
    for (MainWindow* mw : ProjucerApplication::getApp().mainWindowList.windows)
        if (mw->getProject() == &project)
            return mw->getProjectContentComponent();

    return nullptr;
}

CompileEngineChildProcess::Editor* CompileEngineChildProcess::getOrOpenEditorFor (const File& file)
{
    for (Editor* ed : editors)
        if (ed->file == file)
            return ed;

    if (ProjectContentComponent* pcc = findProjectContentComponent())
        if (pcc->showEditorForFile (file, false))
            return getOrOpenEditorFor (file);

    return nullptr;
}

void CompileEngineChildProcess::handleHighlightCode (const SourceCodeRange& location)
{
    ProjectContentComponent* pcc = findProjectContentComponent();

    if (pcc != nullptr && pcc->showEditorForFile (location.file, false))
    {
        SourceCodeEditor* sce = dynamic_cast <SourceCodeEditor*> (pcc->getEditorComponent());

        if (sce != nullptr && sce->editor != nullptr)
        {
            sce->highlight (location.range, true);

            Process::makeForegroundProcess();

            CodeEditorComponent& ed = *sce->editor;
            ed.getTopLevelComponent()->toFront (false);
            ed.grabKeyboardFocus();
        }
    }
}

void CompileEngineChildProcess::cleanAllCachedFilesForProject (Project& p)
{
    File cacheFolder (getCacheLocationForProject (p));

    if (cacheFolder.isDirectory())
        cacheFolder.deleteRecursively();
}