File: projucer_CompileEngineClient.cpp

package info (click to toggle)
juce 4.3.0~repack-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 62,060 kB
  • ctags: 38,418
  • sloc: cpp: 290,180; java: 3,322; makefile: 338; xml: 277; ansic: 255; sh: 182; python: 135
file content (934 lines) | stat: -rw-r--r-- 30,362 bytes parent folder | download
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
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
/*
  ==============================================================================

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

   Permission is granted to use this software under the terms of either:
   a) the GPL v2 (or any later version)
   b) the Affero GPL v3

   Details of these licenses can be found at: www.gnu.org/licenses

   JUCE 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.

   ------------------------------------------------------------------------------

   To release a closed-source product which uses JUCE, commercial licenses are
   available: visit www.juce.com for more information.

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

#include "../jucer_Headers.h"
#include "../Application/jucer_Application.h"
#include "../Project Saving/jucer_ProjectExporter.h"
#include "projucer_MessageIDs.h"
#include "projucer_CppHelpers.h"
#include "projucer_SourceCodeRange.h"
#include "projucer_ClassDatabase.h"
#include "projucer_DiagnosticMessage.h"
#include "projucer_ProjectBuildInfo.h"
#include "projucer_ClientServerMessages.h"
#include "projucer_CompileEngineClient.h"
#include "../LiveBuildEngine/projucer_CompileEngineServer.h"

#ifndef RUN_CLANG_IN_CHILD_PROCESS
 #error
#endif


//==============================================================================
namespace ProjectProperties
{
    const Identifier liveSettingsType ("LIVE_SETTINGS");
   #if JUCE_MAC
    const Identifier liveSettingsSubtype ("OSX");
   #elif JUCE_WINDOWS
    const Identifier liveSettingsSubtype ("WINDOWS");
   #elif JUCE_LINUX
    const Identifier liveSettingsSubtype ("LINUX");
   #endif

    static ValueTree getLiveSettings (Project& project)
    {
        return project.getProjectRoot().getOrCreateChildWithName (liveSettingsType, nullptr)
                                       .getOrCreateChildWithName (liveSettingsSubtype, nullptr);
    }

    static const ValueTree getLiveSettingsConst (Project& project)
    {
        return project.getProjectRoot().getChildWithName (liveSettingsType)
                                       .getChildWithName (liveSettingsSubtype);
    }

    static Value getLiveSetting    (Project& p, const Identifier& i)  { return getLiveSettings (p).getPropertyAsValue (i, p.getUndoManagerFor (getLiveSettings (p))); }
    static var   getLiveSettingVar (Project& p, const Identifier& i)  { return getLiveSettingsConst (p) [i]; }

    static Value  getUserHeaderPathValue (Project& p)          { return getLiveSetting    (p, Ids::headerPath); }
    static String getUserHeaderPathString (Project& p)         { return getLiveSettingVar (p, Ids::headerPath); }
    static Value  getSystemHeaderPathValue (Project& p)        { return getLiveSetting    (p, Ids::systemHeaderPath); }
    static String getSystemHeaderPathString (Project& p)       { return getLiveSettingVar (p, Ids::systemHeaderPath); }
    static Value  getExtraDLLsValue (Project& p)               { return getLiveSetting    (p, Ids::extraDLLs); }
    static String getExtraDLLsString (Project& p)              { return getLiveSettingVar (p, Ids::extraDLLs); }
    static Value  getExtraCompilerFlagsValue (Project& p)      { return getLiveSetting    (p, Ids::extraCompilerFlags); }
    static String getExtraCompilerFlagsString (Project& p)     { return getLiveSettingVar (p, Ids::extraCompilerFlags); }
    static Value  getExtraPreprocessorDefsValue (Project& p)   { return getLiveSetting    (p, Ids::defines); }
    static String getExtraPreprocessorDefsString (Project& p)  { return getLiveSettingVar (p, Ids::defines); }

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

    static File getCacheLocation (Project& project)
    {
        String cacheFolderName = project.getProjectFilenameRoot() + "_" + project.getProjectUID();

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

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

//==============================================================================
void LiveBuildProjectSettings::getLiveSettings (Project& project, PropertyListBuilder& props)
{
    using namespace ProjectProperties;

    props.addSearchPathProperty (getUserHeaderPathValue (project), "User header paths", "User header search paths.");
    props.addSearchPathProperty (getSystemHeaderPathValue (project), "System header paths", "System header search paths.");

    props.add (new TextPropertyComponent (getExtraPreprocessorDefsValue (project), "Preprocessor Definitions", 32768, true),
               "Extra preprocessor definitions. Use the form \"NAME1=value NAME2=value\", using whitespace or commas "
               "to separate the items - to include a space or comma in a definition, precede it with a backslash.");

    props.add (new TextPropertyComponent (getExtraCompilerFlagsValue (project), "Extra compiler flags", 2048, true),
               "Extra command-line flags to be passed to the compiler. This string can contain references to preprocessor"
               " definitions in the form ${NAME_OF_DEFINITION}, which will be replaced with their values.");

    props.add (new TextPropertyComponent (getExtraDLLsValue (project), "Extra dynamic libraries", 2048, true),
               "Extra dynamic libs that the running code may require. Use new-lines or commas to separate the items");
}

void LiveBuildProjectSettings::updateNewlyOpenedProject (Project&) { /* placeholder */ }

bool LiveBuildProjectSettings::isBuildDisabled (Project& p)
{
    const bool defaultBuildDisabled = true;
    return p.getStoredProperties().getBoolValue ("buildDisabled", defaultBuildDisabled);
}

void LiveBuildProjectSettings::setBuildDisabled (Project& p, bool b)    { p.getStoredProperties().setValue ("buildDisabled", b); }
bool LiveBuildProjectSettings::areWarningsDisabled (Project& p)         { return p.getStoredProperties().getBoolValue ("warningsDisabled"); }
void LiveBuildProjectSettings::setWarningsDisabled (Project& p, bool b) { p.getStoredProperties().setValue ("warningsDisabled", b); }

//==============================================================================
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...");
        const String pipeName ("ipc_" + String::toHexString (Random().nextInt64()));

        const String command (createCommandLineForLaunchingServer (pipeName,
                                                                   owner.project.getProjectUID(),
                                                                   ProjectProperties::getCacheLocation (owner.project)));

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

        bool ok = connectToPipe (pipeName, 10000);
        jassert (ok);

        if (ok)
            MessageTypes::sendPing (*this);

        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()    { 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 = nullptr;
    }

    void restartServer()
    {
        server = nullptr;
        server = 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 (project));
        build.setCompileFlags (ProjectProperties::getExtraCompilerFlagsString (project).trim());
        build.setExtraDLLs (getExtraDLLs());
        build.setJuceModulesFolder (EnabledModuleList::findDefaultModulesFolder (project).getFullPathName());

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

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

    ScopedPointer<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              {}

    static String getGlobalDefs (Project& proj)
    {
        String defs (ProjectProperties::getExtraPreprocessorDefsString (proj));

        for (Project::ExporterIterator exporter (proj); exporter.next();)
            if (exporter->canLaunchProject())
                defs << " " << exporter->getExporterIdentifierMacro() << "=1";

        return defs;
    }

    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())
        {
            const File f (projectItem.getFile());

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

        if (projectItem.shouldBeAddedToTargetProject() && ! projectItem.shouldBeAddedToBinaryResources())
        {
            const File f (projectItem.getFile());

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

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

        {
            OwnedArray<LibraryModule> modules;
            proj.getModules().createRequiredModules (modules);

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

                        m->findAndAddCompiledUnits (*exporter, nullptr, compileUnits);
                    }

                    break;
                }
            }
        }

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

            compileUnits.add (binaryDataCpp);
        }

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

        build.setFiles (compileUnits, userFiles);
    }

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

        ScopedPointer<XmlElement> xml (XmlDocument::parse (project.getFile()));

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

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

        return liveModules.isEquivalentTo (diskModules);
    }

    static bool areAnyModulesMissing (Project& project)
    {
        OwnedArray<LibraryModule> modules;
        project.getModules().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 (ProjectProperties::getUserHeaderPathString (project)));
        return convertSearchPathsToAbsolute (paths);
    }

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

        if (project.getProjectType().isAudioPlugin())
        {
            paths.add (getAppSettings().getGlobalPath (Ids::vst3Path, TargetOS::getThisOS()).toString());
        }

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

        for (auto* module : modules)
            paths.addIfNotAlreadyThere (module->getFolder().getParentDirectory().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()
    {
        StringArray dlls;
        dlls.addTokens (ProjectProperties::getExtraDLLsString (project), "\n\r,", StringRef());
        dlls.trim();
        dlls.removeEmptyStrings();
        return dlls;
    }

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChildProcess)
};

//==============================================================================
CompileEngineChildProcess::CompileEngineChildProcess (Project& p)
    : project (p),
      continuousRebuild (false)
{
    ProjucerApplication::getApp().openDocumentManager.addListener (this);

    createProcess();

    errorList.setWarningsEnabled (! LiveBuildProjectSettings::areWarningsDisabled (project));
}

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

    process = nullptr;
    lastComponentList.clear();
}

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

    if (! process->openedOk)
        process = nullptr;

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

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

void CompileEngineChildProcess::handleAppQuit()
{
    DBG ("handleAppQuit");
    runningAppProcess = nullptr;
}

//==============================================================================
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.continuousRebuild)
            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()
{
    if (errorList.getNumErrors() > 0)
        ProjucerApplication::getCommandManager().invokeDirectly (CommandIDs::showBuildTab, true);

    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::setContinuousRebuild (bool b)
{
    continuousRebuild = b;
}

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 (ProjectProperties::getCacheLocation (p));

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