Browse Source

Improved the coding standards used in the juce demo project.

tags/2021-05-28
Julian Storer 15 years ago
parent
commit
5c49cdba8a
19 changed files with 519 additions and 584 deletions
  1. +0
    -1
      extras/juce demo/Source/demos/AudioDemoLatencyPage.cpp
  2. +1
    -1
      extras/juce demo/Source/demos/AudioDemoLatencyPage.h
  3. +1
    -4
      extras/juce demo/Source/demos/AudioDemoPlaybackPage.cpp
  4. +1
    -1
      extras/juce demo/Source/demos/AudioDemoPlaybackPage.h
  5. +4
    -9
      extras/juce demo/Source/demos/AudioDemoSynthPage.cpp
  6. +1
    -1
      extras/juce demo/Source/demos/AudioDemoSynthPage.h
  7. +38
    -41
      extras/juce demo/Source/demos/CameraDemo.cpp
  8. +10
    -13
      extras/juce demo/Source/demos/CodeEditorDemo.cpp
  9. +8
    -12
      extras/juce demo/Source/demos/DragAndDropDemo.cpp
  10. +54
    -51
      extras/juce demo/Source/demos/FontsAndTextDemo.cpp
  11. +93
    -107
      extras/juce demo/Source/demos/InterprocessCommsDemo.cpp
  12. +15
    -17
      extras/juce demo/Source/demos/OpenGLDemo.cpp
  13. +20
    -25
      extras/juce demo/Source/demos/QuickTimeDemo.cpp
  14. +1
    -5
      extras/juce demo/Source/demos/RenderingTestComponent.cpp
  15. +17
    -22
      extras/juce demo/Source/demos/TableDemo.cpp
  16. +47
    -50
      extras/juce demo/Source/demos/ThreadingDemo.cpp
  17. +52
    -64
      extras/juce demo/Source/demos/TreeViewDemo.cpp
  18. +27
    -27
      extras/juce demo/Source/demos/WebBrowserDemo.cpp
  19. +129
    -133
      extras/juce demo/Source/demos/WidgetsDemo.cpp

+ 0
- 1
extras/juce demo/Source/demos/AudioDemoLatencyPage.cpp View File

@@ -324,7 +324,6 @@ AudioDemoLatencyPage::~AudioDemoLatencyPage()
deviceManager.removeAudioCallback (liveAudioDisplayComp); deviceManager.removeAudioCallback (liveAudioDisplayComp);
deviceManager.removeAudioCallback (latencyTester); deviceManager.removeAudioCallback (latencyTester);
delete latencyTester;
//[/Destructor_pre] //[/Destructor_pre]
deleteAndZero (liveAudioDisplayComp); deleteAndZero (liveAudioDisplayComp);


+ 1
- 1
extras/juce demo/Source/demos/AudioDemoLatencyPage.h View File

@@ -61,7 +61,7 @@ public:
private: private:
//[UserVariables] -- You can add your own custom variables in this section. //[UserVariables] -- You can add your own custom variables in this section.
AudioDeviceManager& deviceManager; AudioDeviceManager& deviceManager;
LatencyTester* latencyTester;
ScopedPointer<LatencyTester> latencyTester;
//[/UserVariables] //[/UserVariables]
//============================================================================== //==============================================================================


+ 1
- 4
extras/juce demo/Source/demos/AudioDemoPlaybackPage.cpp View File

@@ -185,7 +185,6 @@ AudioDemoPlaybackPage::AudioDemoPlaybackPage (AudioDeviceManager& deviceManager_
deviceManager.addAudioCallback (&audioSourcePlayer); deviceManager.addAudioCallback (&audioSourcePlayer);
audioSourcePlayer.setSource (&transportSource); audioSourcePlayer.setSource (&transportSource);
currentAudioFileSource = 0;
//[/Constructor] //[/Constructor]
} }
@@ -197,8 +196,6 @@ AudioDemoPlaybackPage::~AudioDemoPlaybackPage()
deviceManager.removeAudioCallback (&audioSourcePlayer); deviceManager.removeAudioCallback (&audioSourcePlayer);
fileTreeComp->removeListener (this); fileTreeComp->removeListener (this);
deleteAndZero (currentAudioFileSource);
//[/Destructor_pre] //[/Destructor_pre]
deleteAndZero (zoomLabel); deleteAndZero (zoomLabel);
@@ -293,7 +290,7 @@ void AudioDemoPlaybackPage::loadFileIntoTransport (const File& audioFile)
// unload the previous file source and delete it.. // unload the previous file source and delete it..
transportSource.stop(); transportSource.stop();
transportSource.setSource (0); transportSource.setSource (0);
deleteAndZero (currentAudioFileSource);
currentAudioFileSource = 0;
// get a format manager and set it up with the basic types (wav and aiff). // get a format manager and set it up with the basic types (wav and aiff).
AudioFormatManager formatManager; AudioFormatManager formatManager;


+ 1
- 1
extras/juce demo/Source/demos/AudioDemoPlaybackPage.h View File

@@ -74,7 +74,7 @@ private:
AudioSourcePlayer audioSourcePlayer; AudioSourcePlayer audioSourcePlayer;
AudioTransportSource transportSource; AudioTransportSource transportSource;
AudioFormatReaderSource* currentAudioFileSource;
ScopedPointer<AudioFormatReaderSource> currentAudioFileSource;
void loadFileIntoTransport (const File& audioFile); void loadFileIntoTransport (const File& audioFile);
//[/UserVariables] //[/UserVariables]


+ 4
- 9
extras/juce demo/Source/demos/AudioDemoSynthPage.cpp View File

@@ -194,11 +194,10 @@ public:
WavAudioFormat wavFormat; WavAudioFormat wavFormat;
AudioFormatReader* audioReader
= wavFormat.createReaderFor (new MemoryInputStream (BinaryData::cello_wav,
BinaryData::cello_wavSize,
false),
true);
ScopedPointer<AudioFormatReader> audioReader (wavFormat.createReaderFor (new MemoryInputStream (BinaryData::cello_wav,
BinaryData::cello_wavSize,
false),
true));
BigInteger allNotes; BigInteger allNotes;
allNotes.setRange (0, 128, true); allNotes.setRange (0, 128, true);
@@ -211,8 +210,6 @@ public:
0.1, // release time 0.1, // release time
10.0 // maximum sample length 10.0 // maximum sample length
)); ));
delete audioReader;
} }
void prepareToPlay (int /*samplesPerBlockExpected*/, double sampleRate) void prepareToPlay (int /*samplesPerBlockExpected*/, double sampleRate)
@@ -296,8 +293,6 @@ AudioDemoSynthPage::~AudioDemoSynthPage()
deviceManager.removeMidiInputCallback (String::empty, &(synthAudioSource->midiCollector)); deviceManager.removeMidiInputCallback (String::empty, &(synthAudioSource->midiCollector));
deviceManager.removeAudioCallback (&audioSourcePlayer); deviceManager.removeAudioCallback (&audioSourcePlayer);
deviceManager.removeAudioCallback (liveAudioDisplayComp); deviceManager.removeAudioCallback (liveAudioDisplayComp);
delete synthAudioSource;
//[/Destructor_pre] //[/Destructor_pre]
deleteAndZero (keyboardComponent); deleteAndZero (keyboardComponent);


+ 1
- 1
extras/juce demo/Source/demos/AudioDemoSynthPage.h View File

@@ -63,7 +63,7 @@ private:
AudioDeviceManager& deviceManager; AudioDeviceManager& deviceManager;
MidiKeyboardState keyboardState; MidiKeyboardState keyboardState;
AudioSourcePlayer audioSourcePlayer; AudioSourcePlayer audioSourcePlayer;
SynthAudioSource* synthAudioSource;
ScopedPointer<SynthAudioSource> synthAudioSource;
//[/UserVariables] //[/UserVariables]
//============================================================================== //==============================================================================


+ 38
- 41
extras/juce demo/Source/demos/CameraDemo.cpp View File

@@ -37,33 +37,31 @@ class CameraDemo : public Component,
public: public:
//============================================================================== //==============================================================================
CameraDemo() CameraDemo()
: cameraSelectorComboBox ("Camera"),
snapshotButton ("Take a snapshot"),
recordMovieButton ("Record a movie file (to your desktop)..."),
recordingMovie (false)
{ {
setName ("Camera"); setName ("Camera");
cameraDevice = 0;
cameraPreviewComp = 0;
recordingMovie = false;
addAndMakeVisible (cameraSelectorComboBox = new ComboBox ("Camera"));
addAndMakeVisible (&cameraSelectorComboBox);
createListOfCameras(); createListOfCameras();
cameraSelectorComboBox->setSelectedId (1);
cameraSelectorComboBox->addListener (this);
cameraSelectorComboBox.setSelectedId (1);
cameraSelectorComboBox.addListener (this);
addAndMakeVisible (snapshotButton = new TextButton ("Take a snapshot"));
snapshotButton->addButtonListener (this);
snapshotButton->setEnabled (false);
addAndMakeVisible (&snapshotButton);
snapshotButton.addButtonListener (this);
snapshotButton.setEnabled (false);
addAndMakeVisible (recordMovieButton = new TextButton ("Record a movie file (to your desktop)..."));
recordMovieButton->addButtonListener (this);
recordMovieButton->setEnabled (false);
addAndMakeVisible (&recordMovieButton);
recordMovieButton.addButtonListener (this);
recordMovieButton.setEnabled (false);
cameraSelectorComboBox->setSelectedId (2);
cameraSelectorComboBox.setSelectedId (2);
} }
~CameraDemo() ~CameraDemo()
{ {
deleteAllChildren();
delete cameraDevice;
} }
void paint (Graphics& g) void paint (Graphics& g)
@@ -76,11 +74,11 @@ public:
void resized() void resized()
{ {
cameraSelectorComboBox->setBounds (10, 4, 250, 24);
snapshotButton->changeWidthToFitText (24);
snapshotButton->setTopLeftPosition (cameraSelectorComboBox->getRight() + 20, 4);
recordMovieButton->changeWidthToFitText (24);
recordMovieButton->setTopLeftPosition (snapshotButton->getRight() + 20, 4);
cameraSelectorComboBox.setBounds (10, 4, 250, 24);
snapshotButton.changeWidthToFitText (24);
snapshotButton.setTopLeftPosition (cameraSelectorComboBox.getRight() + 20, 4);
recordMovieButton.changeWidthToFitText (24);
recordMovieButton.setTopLeftPosition (snapshotButton.getRight() + 20, 4);
if (cameraPreviewComp != 0) if (cameraPreviewComp != 0)
cameraPreviewComp->setBounds (10, 40, getWidth() / 2 - 20, getHeight() - 50); cameraPreviewComp->setBounds (10, 40, getWidth() / 2 - 20, getHeight() - 50);
@@ -89,42 +87,42 @@ public:
void comboBoxChanged (ComboBox*) void comboBoxChanged (ComboBox*)
{ {
// This is called when the user chooses a camera from the drop-down list. // This is called when the user chooses a camera from the drop-down list.
deleteAndZero (cameraDevice);
deleteAndZero (cameraPreviewComp);
cameraDevice = 0;
cameraPreviewComp = 0;
recordingMovie = false; recordingMovie = false;
if (cameraSelectorComboBox->getSelectedId() > 1)
if (cameraSelectorComboBox.getSelectedId() > 1)
{ {
// Try to open the user's choice of camera.. // Try to open the user's choice of camera..
cameraDevice = CameraDevice::openDevice (cameraSelectorComboBox->getSelectedId() - 2);
cameraDevice = CameraDevice::openDevice (cameraSelectorComboBox.getSelectedId() - 2);
// and if it worked, create a preview component for it.. // and if it worked, create a preview component for it..
if (cameraDevice != 0) if (cameraDevice != 0)
addAndMakeVisible (cameraPreviewComp = cameraDevice->createViewerComponent()); addAndMakeVisible (cameraPreviewComp = cameraDevice->createViewerComponent());
} }
snapshotButton->setEnabled (cameraDevice != 0);
recordMovieButton->setEnabled (cameraDevice != 0);
snapshotButton.setEnabled (cameraDevice != 0);
recordMovieButton.setEnabled (cameraDevice != 0);
resized(); resized();
} }
void createListOfCameras() void createListOfCameras()
{ {
cameraSelectorComboBox->clear();
cameraSelectorComboBox->addItem ("No camera", 1);
cameraSelectorComboBox->addSeparator();
cameraSelectorComboBox.clear();
cameraSelectorComboBox.addItem ("No camera", 1);
cameraSelectorComboBox.addSeparator();
StringArray cameras = CameraDevice::getAvailableDevices(); StringArray cameras = CameraDevice::getAvailableDevices();
for (int i = 0; i < cameras.size(); ++i) for (int i = 0; i < cameras.size(); ++i)
cameraSelectorComboBox->addItem (cameras[i], i + 2);
cameraSelectorComboBox.addItem (cameras[i], i + 2);
} }
void buttonClicked (Button* b) void buttonClicked (Button* b)
{ {
if (cameraDevice != 0) if (cameraDevice != 0)
{ {
if (b == recordMovieButton)
if (b == &recordMovieButton)
{ {
// The user has clicked the record movie button.. // The user has clicked the record movie button..
if (! recordingMovie) if (! recordingMovie)
@@ -137,14 +135,14 @@ public:
CameraDevice::getFileExtension())); CameraDevice::getFileExtension()));
cameraDevice->startRecordingToFile (file); cameraDevice->startRecordingToFile (file);
recordMovieButton->setButtonText ("Stop Recording");
recordMovieButton.setButtonText ("Stop Recording");
} }
else else
{ {
// Already recording, so stop... // Already recording, so stop...
recordingMovie = false; recordingMovie = false;
cameraDevice->stopRecording(); cameraDevice->stopRecording();
recordMovieButton->setButtonText ("Start recording (to a file on your desktop)");
recordMovieButton.setButtonText ("Start recording (to a file on your desktop)");
} }
} }
else else
@@ -173,15 +171,14 @@ public:
private: private:
//============================================================================== //==============================================================================
CameraDevice* cameraDevice;
ScopedPointer<CameraDevice> cameraDevice;
ScopedPointer<Component> cameraPreviewComp;
Image lastSnapshot;
ComboBox* cameraSelectorComboBox;
TextButton* snapshotButton;
TextButton* recordMovieButton;
Component* cameraPreviewComp;
ComboBox cameraSelectorComboBox;
TextButton snapshotButton;
TextButton recordMovieButton;
bool recordingMovie; bool recordingMovie;
Image lastSnapshot;
}; };


+ 10
- 13
extras/juce demo/Source/demos/CodeEditorDemo.cpp View File

@@ -33,32 +33,29 @@ class CodeEditorDemo : public Component,
public: public:
//============================================================================== //==============================================================================
CodeEditorDemo() CodeEditorDemo()
: fileChooser ("File", File::nonexistent, true, false, false,
"*.cpp;*.h;*.hpp;*.c;*.mm;*.m", String::empty,
"Choose a C++ file to open it in the editor")
{ {
setName ("Code Editor"); setName ("Code Editor");
setOpaque (true); setOpaque (true);
// Create the editor.. // Create the editor..
addAndMakeVisible (editor = new CodeEditorComponent (codeDocument, &cppTokeniser)); addAndMakeVisible (editor = new CodeEditorComponent (codeDocument, &cppTokeniser));
editor->loadContent ("\n\n/* Code editor demo! Please be gentle, this component is still an alpha version! */\n\n");
// Create a file chooser control to load files into it.. // Create a file chooser control to load files into it..
addAndMakeVisible (fileChooser = new FilenameComponent ("File", File::nonexistent, true, false, false,
"*.cpp;*.h;*.hpp;*.c;*.mm;*.m", String::empty,
"Choose a C++ file to open it in the editor"));
fileChooser->addListener (this);
editor->loadContent ("\n\n/* Code editor demo! Please be gentle, this component is still an alpha version! */\n\n");
addAndMakeVisible (&fileChooser);
fileChooser.addListener (this);
} }
~CodeEditorDemo() ~CodeEditorDemo()
{ {
deleteAllChildren();
} }
void filenameComponentChanged (FilenameComponent*) void filenameComponentChanged (FilenameComponent*)
{ {
File f (fileChooser->getCurrentFile());
editor->loadContent (f.loadFileAsString());
editor->loadContent (fileChooser.getCurrentFile().loadFileAsString());
} }
void paint (Graphics& g) void paint (Graphics& g)
@@ -69,7 +66,7 @@ public:
void resized() void resized()
{ {
editor->setBounds (10, 45, getWidth() - 20, getHeight() - 55); editor->setBounds (10, 45, getWidth() - 20, getHeight() - 55);
fileChooser->setBounds (10, 10, getWidth() - 20, 25);
fileChooser.setBounds (10, 10, getWidth() - 20, 25);
} }
//============================================================================== //==============================================================================
@@ -83,9 +80,9 @@ private:
CPlusPlusCodeTokeniser cppTokeniser; CPlusPlusCodeTokeniser cppTokeniser;
// the editor component // the editor component
CodeEditorComponent* editor;
ScopedPointer<CodeEditorComponent> editor;
FilenameComponent* fileChooser;
FilenameComponent fileChooser;
}; };


+ 8
- 12
extras/juce demo/Source/demos/DragAndDropDemo.cpp View File

@@ -211,38 +211,34 @@ private:
class DragAndDropDemo : public Component, class DragAndDropDemo : public Component,
public DragAndDropContainer public DragAndDropContainer
{ {
//==============================================================================
DragAndDropDemoSource* source;
DragAndDropDemoTarget* target;
public: public:
//============================================================================== //==============================================================================
DragAndDropDemo() DragAndDropDemo()
{ {
setName ("Drag-and-Drop"); setName ("Drag-and-Drop");
source = new DragAndDropDemoSource();
addAndMakeVisible (source);
target = new DragAndDropDemoTarget();
addAndMakeVisible (target);
addAndMakeVisible (&source);
addAndMakeVisible (&target);
} }
~DragAndDropDemo() ~DragAndDropDemo()
{ {
deleteAllChildren();
} }
void resized() void resized()
{ {
source->setBounds (10, 10, 250, 150);
target->setBounds (getWidth() - 260, getHeight() - 160, 250, 150);
source.setBounds (10, 10, 250, 150);
target.setBounds (getWidth() - 260, getHeight() - 160, 250, 150);
} }
//============================================================================== //==============================================================================
// (need to put this in to disambiguate the new/delete operators used in the // (need to put this in to disambiguate the new/delete operators used in the
// two base classes). // two base classes).
juce_UseDebuggingNewOperator juce_UseDebuggingNewOperator
private:
DragAndDropDemoSource source;
DragAndDropDemoTarget target;
}; };


+ 54
- 51
extras/juce demo/Source/demos/FontsAndTextDemo.cpp View File

@@ -32,22 +32,14 @@ class FontsAndTextDemo : public Component,
public ButtonListener, public ButtonListener,
public SliderListener public SliderListener
{ {
Array<Font> fonts;
ListBox* listBox;
TextEditor* textBox;
ToggleButton* boldButton;
ToggleButton* italicButton;
Slider* sizeSlider;
Slider* kerningSlider;
Slider* horizontalScaleSlider;
StretchableLayoutManager verticalLayout;
StretchableLayoutResizerBar* verticalDividerBar;
public: public:
//============================================================================== //==============================================================================
FontsAndTextDemo() FontsAndTextDemo()
: boldButton ("Bold"),
italicButton ("Italic"),
sizeLabel (String::empty, "Size"),
kerningLabel (String::empty, "Kerning"),
horizontalScaleLabel (String::empty, "Scale")
{ {
setName ("Fonts"); setName ("Fonts");
@@ -56,38 +48,38 @@ public:
addAndMakeVisible (listBox = new ListBox ("fonts", this)); addAndMakeVisible (listBox = new ListBox ("fonts", this));
listBox->setRowHeight (28); listBox->setRowHeight (28);
addAndMakeVisible (textBox = new TextEditor());
addAndMakeVisible (&textBox);
textBox->setColour (TextEditor::backgroundColourId, Colours::white);
textBox->setColour (TextEditor::outlineColourId, Colours::black.withAlpha (0.5f));
textBox.setColour (TextEditor::backgroundColourId, Colours::white);
textBox.setColour (TextEditor::outlineColourId, Colours::black.withAlpha (0.5f));
textBox->setMultiLine (true, true);
textBox->setReturnKeyStartsNewLine (true);
textBox->setText ("The Quick Brown Fox Jumps Over The Lazy Dog\n\nAa Bb Cc Dd Ee Ff Gg Hh Ii Jj Kk Ll Mm Nn Oo Pp Qq Rr Ss Tt Uu Vv Ww Xx Yy Zz 0123456789");
textBox.setMultiLine (true, true);
textBox.setReturnKeyStartsNewLine (true);
textBox.setText ("The Quick Brown Fox Jumps Over The Lazy Dog\n\nAa Bb Cc Dd Ee Ff Gg Hh Ii Jj Kk Ll Mm Nn Oo Pp Qq Rr Ss Tt Uu Vv Ww Xx Yy Zz 0123456789");
addAndMakeVisible (boldButton = new ToggleButton ("bold"));
boldButton->addButtonListener (this);
addAndMakeVisible (&boldButton);
boldButton.addButtonListener (this);
addAndMakeVisible (italicButton = new ToggleButton ("italic"));
italicButton->addButtonListener (this);
addAndMakeVisible (&italicButton);
italicButton.addButtonListener (this);
addAndMakeVisible (sizeSlider = new Slider ("Size"));
sizeSlider->setRange (3.0, 150.0, 0.1);
sizeSlider->setValue (20.0);
sizeSlider->addListener (this);
(new Label (String::empty, sizeSlider->getName()))->attachToComponent (sizeSlider, true);
addAndMakeVisible (&sizeSlider);
sizeSlider.setRange (3.0, 150.0, 0.1);
sizeSlider.setValue (20.0);
sizeSlider.addListener (this);
sizeLabel.attachToComponent (&sizeSlider, true);
addAndMakeVisible (kerningSlider = new Slider ("Kerning"));
kerningSlider->setRange (-1.0, 1.0, 0.01);
kerningSlider->setValue (0.0);
kerningSlider->addListener (this);
(new Label (String::empty, kerningSlider->getName()))->attachToComponent (kerningSlider, true);
addAndMakeVisible (&kerningSlider);
kerningSlider.setRange (-1.0, 1.0, 0.01);
kerningSlider.setValue (0.0);
kerningSlider.addListener (this);
kerningLabel.attachToComponent (&kerningSlider, true);
addAndMakeVisible (horizontalScaleSlider = new Slider ("Stretch"));
horizontalScaleSlider->setRange (0.1, 4.0, 0.01);
horizontalScaleSlider->setValue (1.0);
horizontalScaleSlider->addListener (this);
(new Label (String::empty, horizontalScaleSlider->getName()))->attachToComponent (horizontalScaleSlider, true);
addAndMakeVisible (&horizontalScaleSlider);
horizontalScaleSlider.setRange (0.1, 4.0, 0.01);
horizontalScaleSlider.setValue (1.0);
horizontalScaleSlider.addListener (this);
horizontalScaleLabel.attachToComponent (&horizontalScaleSlider, true);
listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.5f)); listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.5f));
listBox->setOutlineThickness (1); listBox->setOutlineThickness (1);
@@ -107,7 +99,6 @@ public:
~FontsAndTextDemo() ~FontsAndTextDemo()
{ {
deleteAllChildren();
} }
void resized() void resized()
@@ -122,13 +113,13 @@ public:
// now lay out the text box and the controls below it.. // now lay out the text box and the controls below it..
int x = verticalLayout.getItemCurrentPosition (2) + 4; int x = verticalLayout.getItemCurrentPosition (2) + 4;
textBox->setBounds (x, 0, getWidth() - x, getHeight() - 110);
textBox.setBounds (x, 0, getWidth() - x, getHeight() - 110);
x += 70; x += 70;
sizeSlider->setBounds (x, getHeight() - 106, getWidth() - x, 22);
kerningSlider->setBounds (x, getHeight() - 82, getWidth() - x, 22);
horizontalScaleSlider->setBounds (x, getHeight() - 58, getWidth() - x, 22);
boldButton->setBounds (x, getHeight() - 34, (getWidth() - x) / 2, 22);
italicButton->setBounds (x + (getWidth() - x) / 2, getHeight() - 34, (getWidth() - x) / 2, 22);
sizeSlider.setBounds (x, getHeight() - 106, getWidth() - x, 22);
kerningSlider.setBounds (x, getHeight() - 82, getWidth() - x, 22);
horizontalScaleSlider.setBounds (x, getHeight() - 58, getWidth() - x, 22);
boldButton.setBounds (x, getHeight() - 34, (getWidth() - x) / 2, 22);
italicButton.setBounds (x + (getWidth() - x) / 2, getHeight() - 34, (getWidth() - x) / 2, 22);
} }
// implements the ListBoxModel method // implements the ListBoxModel method
@@ -167,13 +158,13 @@ public:
{ {
Font font (fonts [listBox->getSelectedRow()]); Font font (fonts [listBox->getSelectedRow()]);
font.setHeight ((float) sizeSlider->getValue());
font.setBold (boldButton->getToggleState());
font.setItalic (italicButton->getToggleState());
font.setExtraKerningFactor ((float) kerningSlider->getValue());
font.setHorizontalScale ((float) horizontalScaleSlider->getValue());
font.setHeight ((float) sizeSlider.getValue());
font.setBold (boldButton.getToggleState());
font.setItalic (italicButton.getToggleState());
font.setExtraKerningFactor ((float) kerningSlider.getValue());
font.setHorizontalScale ((float) horizontalScaleSlider.getValue());
textBox->applyFontToAllText (font);
textBox.applyFontToAllText (font);
} }
void selectedRowsChanged (int /*lastRowselected*/) void selectedRowsChanged (int /*lastRowselected*/)
@@ -191,6 +182,18 @@ public:
// (this is called when the size slider is moved) // (this is called when the size slider is moved)
updatePreviewBoxText(); updatePreviewBoxText();
} }
private:
Array<Font> fonts;
ScopedPointer<ListBox> listBox;
TextEditor textBox;
ToggleButton boldButton, italicButton;
Slider sizeSlider, kerningSlider, horizontalScaleSlider;
Label sizeLabel, kerningLabel, horizontalScaleLabel;
StretchableLayoutManager verticalLayout;
ScopedPointer<StretchableLayoutResizerBar> verticalDividerBar;
}; };


+ 93
- 107
extras/juce demo/Source/demos/InterprocessCommsDemo.cpp View File

@@ -34,62 +34,67 @@ class InterprocessCommsDemo : public Component,
public: public:
//============================================================================== //==============================================================================
InterprocessCommsDemo() InterprocessCommsDemo()
: sendButton ("send", "Fires off the message"),
modeLabel (String::empty, "Mode:"),
pipeLabel (String::empty, "Pipe Name:"),
numberLabel (String::empty, "Socket Port:"),
hostLabel (String::empty, "Socket Host:")
{ {
server = new DemoInterprocessConnectionServer (*this);
setName ("Interprocess Communication"); setName ("Interprocess Communication");
server = new DemoInterprocessConnectionServer (*this);
// create all our UI bits and pieces.. // create all our UI bits and pieces..
addAndMakeVisible (modeSelector = new ComboBox ("mode:"));
modeSelector->setBounds (100, 25, 200, 24);
(new Label (modeSelector->getName(), modeSelector->getName()))->attachToComponent (modeSelector, true);
modeSelector->addItem ("(Disconnected)", 8);
modeSelector->addSeparator();
modeSelector->addItem ("Named pipe (listening)", 1);
modeSelector->addItem ("Named pipe (connect to existing pipe)", 5);
modeSelector->addSeparator();
modeSelector->addItem ("Socket (listening)", 2);
modeSelector->addItem ("Socket (connect to existing socket)", 6);
modeSelector->setSelectedId (8);
modeSelector->addListener (this);
addAndMakeVisible (pipeName = new TextEditor ("pipe name:"));
pipeName->setBounds (100, 60, 130, 24);
pipeName->setMultiLine (false);
pipeName->setText ("juce demo pipe");
(new Label (pipeName->getName(), pipeName->getName()))->attachToComponent (pipeName, true);
addAndMakeVisible (socketNumber = new TextEditor ("socket port:"));
socketNumber->setBounds (350, 60, 80, 24);
socketNumber->setMultiLine (false);
socketNumber->setText ("12345");
socketNumber->setInputRestrictions (5, "0123456789");
(new Label (socketNumber->getName(), socketNumber->getName()))->attachToComponent (socketNumber, true);
addAndMakeVisible (socketHost = new TextEditor ("socket host:"));
socketHost->setBounds (530, 60, 130, 24);
socketHost->setMultiLine (false);
socketHost->setText ("localhost");
socketNumber->setInputRestrictions (512);
(new Label (socketHost->getName(), socketHost->getName()))->attachToComponent (socketHost, true);
addChildComponent (sendText = new TextEditor ("sendtext"));
sendText->setBounds (30, 120, 200, 24);
sendText->setMultiLine (false);
sendText->setReadOnly (false);
sendText->setText ("testing 1234");
addChildComponent (sendButton = new TextButton ("send", "Fires off the message"));
sendButton->setBounds (240, 120, 200, 24);
sendButton->changeWidthToFitText();
sendButton->addButtonListener (this);
addChildComponent (incomingMessages = new TextEditor ("messages"));
incomingMessages->setReadOnly (true);
incomingMessages->setMultiLine (true);
incomingMessages->setBounds (30, 150, 500, 250);
addAndMakeVisible (&modeSelector);
modeSelector.setBounds (100, 25, 200, 24);
modeLabel.attachToComponent (&modeSelector, true);
modeSelector.addItem ("(Disconnected)", 8);
modeSelector.addSeparator();
modeSelector.addItem ("Named pipe (listening)", 1);
modeSelector.addItem ("Named pipe (connect to existing pipe)", 5);
modeSelector.addSeparator();
modeSelector.addItem ("Socket (listening)", 2);
modeSelector.addItem ("Socket (connect to existing socket)", 6);
modeSelector.setSelectedId (8);
modeSelector.addListener (this);
addAndMakeVisible (&pipeName);
pipeName.setBounds (100, 60, 130, 24);
pipeName.setMultiLine (false);
pipeName.setText ("juce demo pipe");
pipeLabel.attachToComponent (&pipeName, true);
addAndMakeVisible (&socketNumber);
socketNumber.setBounds (350, 60, 80, 24);
socketNumber.setMultiLine (false);
socketNumber.setText ("12345");
socketNumber.setInputRestrictions (5, "0123456789");
numberLabel.attachToComponent (&socketNumber, true);
addAndMakeVisible (&socketHost);
socketHost.setBounds (530, 60, 130, 24);
socketHost.setMultiLine (false);
socketHost.setText ("localhost");
socketNumber.setInputRestrictions (512);
hostLabel.attachToComponent (&socketHost, true);
addChildComponent (&sendText);
sendText.setBounds (30, 120, 200, 24);
sendText.setMultiLine (false);
sendText.setReadOnly (false);
sendText.setText ("testing 1234");
addChildComponent (&sendButton);
sendButton.setBounds (240, 120, 200, 24);
sendButton.changeWidthToFitText();
sendButton.addButtonListener (this);
addChildComponent (&incomingMessages);
incomingMessages.setReadOnly (true);
incomingMessages.setMultiLine (true);
incomingMessages.setBounds (30, 150, 500, 250);
// call this to set up everything's state correctly. // call this to set up everything's state correctly.
comboBoxChanged (0); comboBoxChanged (0);
@@ -98,18 +103,15 @@ public:
~InterprocessCommsDemo() ~InterprocessCommsDemo()
{ {
close(); close();
delete server;
deleteAllChildren();
} }
void buttonClicked (Button* button) void buttonClicked (Button* button)
{ {
if (button == sendButton)
if (button == &sendButton)
{ {
// The send button has been pressed, so write out the contents of the // The send button has been pressed, so write out the contents of the
// text box to the socket or pipe, depending on which is active. // text box to the socket or pipe, depending on which is active.
const String text (sendText->getText());
const String text (sendText.getText());
MemoryBlock messageData (text.toUTF8(), text.getNumBytesAsUTF8()); MemoryBlock messageData (text.toUTF8(), text.getNumBytesAsUTF8());
for (int i = activeConnections.size(); --i >= 0;) for (int i = activeConnections.size(); --i >= 0;)
@@ -126,7 +128,7 @@ public:
void comboBoxChanged (ComboBox*) void comboBoxChanged (ComboBox*)
{ {
// This is called when the user picks a different mode from the drop-down list.. // This is called when the user picks a different mode from the drop-down list..
const int modeId = modeSelector->getSelectedId();
const int modeId = modeSelector.getSelectedId();
close(); close();
@@ -145,10 +147,10 @@ public:
activeConnections.clear(); activeConnections.clear();
// Reset the UI stuff to a disabled state. // Reset the UI stuff to a disabled state.
sendText->setVisible (false);
sendButton->setVisible (false);
incomingMessages->setText (String::empty, false);
incomingMessages->setVisible (true);
sendText.setVisible (false);
sendButton.setVisible (false);
incomingMessages.setText (String::empty, false);
incomingMessages.setVisible (true);
appendMessage ( appendMessage (
"To demonstrate named pipes, you'll need to run two instances of the JuceDemo application on this machine. On " "To demonstrate named pipes, you'll need to run two instances of the JuceDemo application on this machine. On "
@@ -165,11 +167,11 @@ public:
close(); close();
// Make the appropriate bits of UI visible.. // Make the appropriate bits of UI visible..
sendText->setVisible (true);
sendButton->setVisible (true);
sendText.setVisible (true);
sendButton.setVisible (true);
incomingMessages->setText (String::empty, false);
incomingMessages->setVisible (true);
incomingMessages.setText (String::empty, false);
incomingMessages.setVisible (true);
// and try to open the socket or pipe... // and try to open the socket or pipe...
bool openedOk = false; bool openedOk = false;
@@ -178,23 +180,21 @@ public:
{ {
// if we're connecting to an existing server, we can just create a connection object // if we're connecting to an existing server, we can just create a connection object
// directly. // directly.
DemoInterprocessConnection* newConnection = new DemoInterprocessConnection (*this);
ScopedPointer<DemoInterprocessConnection> newConnection (new DemoInterprocessConnection (*this));
if (asSocket) if (asSocket)
{ {
openedOk = newConnection->connectToSocket (socketHost->getText(),
socketNumber->getText().getIntValue(),
openedOk = newConnection->connectToSocket (socketHost.getText(),
socketNumber.getText().getIntValue(),
1000); 1000);
} }
else else
{ {
openedOk = newConnection->connectToPipe (pipeName->getText());
openedOk = newConnection->connectToPipe (pipeName.getText());
} }
if (openedOk) if (openedOk)
activeConnections.add (newConnection);
else
delete newConnection;
activeConnections.add (newConnection.release());
} }
else else
{ {
@@ -202,32 +202,28 @@ public:
// clients to connect. It'll then create connection objects for us when clients arrive. // clients to connect. It'll then create connection objects for us when clients arrive.
if (asSocket) if (asSocket)
{ {
openedOk = server->beginWaitingForSocket (socketNumber->getText().getIntValue());
openedOk = server->beginWaitingForSocket (socketNumber.getText().getIntValue());
if (openedOk) if (openedOk)
appendMessage ("Waiting for another app to connect to this socket.."); appendMessage ("Waiting for another app to connect to this socket..");
} }
else else
{ {
DemoInterprocessConnection* newConnection = new DemoInterprocessConnection (*this);
ScopedPointer<DemoInterprocessConnection> newConnection (new DemoInterprocessConnection (*this));
openedOk = newConnection->createPipe (pipeName->getText());
openedOk = newConnection->createPipe (pipeName.getText());
if (openedOk) if (openedOk)
{ {
appendMessage ("Waiting for another app to connect to this pipe.."); appendMessage ("Waiting for another app to connect to this pipe..");
activeConnections.add (newConnection);
}
else
{
delete newConnection;
activeConnections.add (newConnection.release());
} }
} }
} }
if (! openedOk) if (! openedOk)
{ {
modeSelector->setSelectedId (8);
modeSelector.setSelectedId (8);
AlertWindow::showMessageBox (AlertWindow::WarningIcon, AlertWindow::showMessageBox (AlertWindow::WarningIcon,
"Interprocess Comms Demo", "Interprocess Comms Demo",
@@ -237,17 +233,14 @@ public:
void appendMessage (const String& message) void appendMessage (const String& message)
{ {
incomingMessages->setCaretPosition (INT_MAX);
incomingMessages->insertTextAtCaret (message + "\n");
incomingMessages->setCaretPosition (INT_MAX);
incomingMessages.setCaretPosition (INT_MAX);
incomingMessages.insertTextAtCaret (message + "\n");
incomingMessages.setCaretPosition (INT_MAX);
} }
//============================================================================== //==============================================================================
class DemoInterprocessConnection : public InterprocessConnection class DemoInterprocessConnection : public InterprocessConnection
{ {
InterprocessCommsDemo& owner;
int ourNumber;
public: public:
DemoInterprocessConnection (InterprocessCommsDemo& owner_) DemoInterprocessConnection (InterprocessCommsDemo& owner_)
: InterprocessConnection (true), : InterprocessConnection (true),
@@ -257,10 +250,6 @@ public:
ourNumber = ++totalConnections; ourNumber = ++totalConnections;
} }
~DemoInterprocessConnection()
{
}
void connectionMade() void connectionMade()
{ {
owner.appendMessage ("Connection #" + String (ourNumber) + " - connection started"); owner.appendMessage ("Connection #" + String (ourNumber) + " - connection started");
@@ -275,23 +264,21 @@ public:
{ {
owner.appendMessage ("Connection #" + String (ourNumber) + " - message received: " + message.toString()); owner.appendMessage ("Connection #" + String (ourNumber) + " - message received: " + message.toString());
} }
private:
InterprocessCommsDemo& owner;
int ourNumber;
}; };
//============================================================================== //==============================================================================
class DemoInterprocessConnectionServer : public InterprocessConnectionServer class DemoInterprocessConnectionServer : public InterprocessConnectionServer
{ {
InterprocessCommsDemo& owner;
public: public:
DemoInterprocessConnectionServer (InterprocessCommsDemo& owner_) DemoInterprocessConnectionServer (InterprocessCommsDemo& owner_)
: owner (owner_) : owner (owner_)
{ {
} }
~DemoInterprocessConnectionServer()
{
}
InterprocessConnection* createConnectionObject() InterprocessConnection* createConnectionObject()
{ {
DemoInterprocessConnection* newConnection = new DemoInterprocessConnection (owner); DemoInterprocessConnection* newConnection = new DemoInterprocessConnection (owner);
@@ -299,6 +286,9 @@ public:
owner.activeConnections.add (newConnection); owner.activeConnections.add (newConnection);
return newConnection; return newConnection;
} }
private:
InterprocessCommsDemo& owner;
}; };
OwnedArray <DemoInterprocessConnection, CriticalSection> activeConnections; OwnedArray <DemoInterprocessConnection, CriticalSection> activeConnections;
@@ -308,16 +298,12 @@ public:
juce_UseDebuggingNewOperator juce_UseDebuggingNewOperator
private: private:
ComboBox* modeSelector;
TextEditor* sendText;
TextButton* sendButton;
TextEditor* incomingMessages;
TextEditor* pipeName;
TextEditor* socketNumber;
TextEditor* socketHost;
ComboBox modeSelector;
TextButton sendButton;
TextEditor sendText, incomingMessages, pipeName, socketNumber, socketHost;
Label modeLabel, pipeLabel, numberLabel, hostLabel;
DemoInterprocessConnectionServer* server;
ScopedPointer<DemoInterprocessConnectionServer> server;
}; };


+ 15
- 17
extras/juce demo/Source/demos/OpenGLDemo.cpp View File

@@ -55,20 +55,16 @@
class DemoOpenGLCanvas : public OpenGLComponent, class DemoOpenGLCanvas : public OpenGLComponent,
public Timer public Timer
{ {
float rotation, delta;
Image image;
public: public:
DemoOpenGLCanvas() DemoOpenGLCanvas()
: rotation (0.0f),
delta (1.0f)
{ {
#if JUCE_IPHONE #if JUCE_IPHONE
// (On the iPhone, choose a format without a depth buffer) // (On the iPhone, choose a format without a depth buffer)
setPixelFormat (OpenGLPixelFormat (8, 8, 0, 0)); setPixelFormat (OpenGLPixelFormat (8, 8, 0, 0));
#endif #endif
rotation = 0.0f;
delta = 1.0f;
image = Image (Image::RGB, 512, 512, true, Image::SoftwareImage); image = Image (Image::RGB, 512, 512, true, Image::SoftwareImage);
Graphics g (image); Graphics g (image);
@@ -259,33 +255,35 @@ public:
repaint(); repaint();
} }
private:
float rotation, delta;
Image image;
}; };
//============================================================================== //==============================================================================
class OpenGLDemo : public Component class OpenGLDemo : public Component
{ {
//==============================================================================
DemoOpenGLCanvas* canvas;
public: public:
//============================================================================== //==============================================================================
OpenGLDemo() OpenGLDemo()
{ {
setName ("OpenGL"); setName ("OpenGL");
canvas = new DemoOpenGLCanvas();
addAndMakeVisible (canvas);
}
~OpenGLDemo()
{
deleteAllChildren();
addAndMakeVisible (&canvas);
} }
void resized() void resized()
{ {
canvas->setBounds (10, 10, getWidth() - 20, getHeight() - 50);
canvas.setBounds (10, 10, getWidth() - 20, getHeight() - 50);
} }
private:
DemoOpenGLCanvas canvas;
OpenGLDemo (const OpenGLDemo&);
OpenGLDemo& operator= (const OpenGLDemo&);
}; };


+ 20
- 25
extras/juce demo/Source/demos/QuickTimeDemo.cpp View File

@@ -34,39 +34,34 @@ class QuickTimeWindowWithFileBrowser : public Component,
{ {
public: public:
QuickTimeWindowWithFileBrowser() QuickTimeWindowWithFileBrowser()
: fileChooser ("movie", File::nonexistent, true, false, false,
"*.*", String::empty, "(choose a video file to play)")
{ {
addAndMakeVisible (qtComp = new QuickTimeMovieComponent());
// and a file-chooser..
addAndMakeVisible (fileChooser = new FilenameComponent ("movie",
File::nonexistent,
true, false, false,
"*.*",
String::empty,
"(choose a video file to play)"));
fileChooser->addListener (this);
fileChooser->setBrowseButtonText ("browse");
addAndMakeVisible (&qtComp);
addAndMakeVisible (&fileChooser);
fileChooser.addListener (this);
fileChooser.setBrowseButtonText ("browse");
} }
~QuickTimeWindowWithFileBrowser() ~QuickTimeWindowWithFileBrowser()
{ {
deleteAllChildren();
} }
void resized() void resized()
{ {
qtComp->setBounds (0, 0, getWidth(), getHeight() - 30);
fileChooser->setBounds (0, getHeight() - 24, getWidth(), 24);
qtComp.setBounds (0, 0, getWidth(), getHeight() - 30);
fileChooser.setBounds (0, getHeight() - 24, getWidth(), 24);
} }
void filenameComponentChanged (FilenameComponent*) void filenameComponentChanged (FilenameComponent*)
{ {
// this is called when the user changes the filename in the file chooser box // this is called when the user changes the filename in the file chooser box
if (qtComp->loadMovie (fileChooser->getCurrentFile(), true))
if (qtComp.loadMovie (fileChooser.getCurrentFile(), true))
{ {
// loaded the file ok, so let's start it playing.. // loaded the file ok, so let's start it playing..
qtComp->play();
qtComp.play();
} }
else else
{ {
@@ -77,8 +72,8 @@ public:
} }
private: private:
QuickTimeMovieComponent* qtComp;
FilenameComponent* fileChooser;
QuickTimeMovieComponent qtComp;
FilenameComponent fileChooser;
}; };
@@ -92,25 +87,25 @@ public:
setName ("QuickTime"); setName ("QuickTime");
// add a movie component.. // add a movie component..
addAndMakeVisible (qtComp1 = new QuickTimeWindowWithFileBrowser());
addAndMakeVisible (qtComp2 = new QuickTimeWindowWithFileBrowser());
addAndMakeVisible (&qtComp1);
addAndMakeVisible (&qtComp2);
} }
~QuickTimeDemo() ~QuickTimeDemo()
{ {
deleteAllChildren();
qtComp1.setVisible (false);
qtComp2.setVisible (false);
} }
void resized() void resized()
{ {
qtComp1->setBoundsRelative (0.05f, 0.05f, 0.425f, 0.9f);
qtComp2->setBoundsRelative (0.525f, 0.05f, 0.425f, 0.9f);
qtComp1.setBoundsRelative (0.05f, 0.05f, 0.425f, 0.9f);
qtComp2.setBoundsRelative (0.525f, 0.05f, 0.425f, 0.9f);
} }
private: private:
//============================================================================== //==============================================================================
QuickTimeWindowWithFileBrowser* qtComp1;
QuickTimeWindowWithFileBrowser* qtComp2;
QuickTimeWindowWithFileBrowser qtComp1, qtComp2;
}; };


+ 1
- 5
extras/juce demo/Source/demos/RenderingTestComponent.cpp View File

@@ -35,7 +35,6 @@ public:
{ {
setOpaque (true); setOpaque (true);
averageTime = 0; averageTime = 0;
svgDrawable = 0;
rgbImage = ImageFileFormat::loadFrom (RenderingTestComponent::demoJpeg_jpg, RenderingTestComponent::demoJpeg_jpgSize); rgbImage = ImageFileFormat::loadFrom (RenderingTestComponent::demoJpeg_jpg, RenderingTestComponent::demoJpeg_jpgSize);
argbImage = ImageFileFormat::loadFrom (RenderingTestComponent::demoPng_png, RenderingTestComponent::demoPng_pngSize); argbImage = ImageFileFormat::loadFrom (RenderingTestComponent::demoPng_png, RenderingTestComponent::demoPng_pngSize);
@@ -68,7 +67,6 @@ public:
~RenderingTestCanvas() ~RenderingTestCanvas()
{ {
delete svgDrawable;
} }
void paint (Graphics& g) void paint (Graphics& g)
@@ -150,7 +148,7 @@ private:
double averageTime; double averageTime;
Image rgbImage, argbImage; Image rgbImage, argbImage;
DrawableComposite* svgDrawable;
ScopedPointer<DrawableComposite> svgDrawable;
GlyphArrangement glyphs; GlyphArrangement glyphs;
ColourGradient linearGradient, radialGradient; ColourGradient linearGradient, radialGradient;
float bouncingPointX[10], bouncingPointY[10], bouncingPointDX[10], bouncingPointDY[10]; float bouncingPointX[10], bouncingPointY[10], bouncingPointDX[10], bouncingPointDY[10];
@@ -327,8 +325,6 @@ private:
void createSVGDrawable() void createSVGDrawable()
{ {
deleteAndZero (svgDrawable);
MemoryInputStream iconsFileStream (BinaryData::icons_zip, BinaryData::icons_zipSize, false); MemoryInputStream iconsFileStream (BinaryData::icons_zip, BinaryData::icons_zipSize, false);
ZipFile icons (&iconsFileStream, false); ZipFile icons (&iconsFileStream, false);


+ 17
- 22
extras/juce demo/Source/demos/TableDemo.cpp View File

@@ -36,8 +36,7 @@ class TableDemoComponent : public Component,
public: public:
//============================================================================== //==============================================================================
TableDemoComponent() TableDemoComponent()
: font (14.0f),
demoData (0)
: font (14.0f)
{ {
// Load some data from an embedded XML file.. // Load some data from an embedded XML file..
loadData(); loadData();
@@ -71,9 +70,6 @@ public:
~TableDemoComponent() ~TableDemoComponent()
{ {
deleteAllChildren();
delete demoData;
} }
//============================================================================== //==============================================================================
@@ -201,10 +197,10 @@ public:
juce_UseDebuggingNewOperator juce_UseDebuggingNewOperator
private: private:
TableListBox* table; // the table component itself
ScopedPointer<TableListBox> table; // the table component itself
Font font; Font font;
XmlElement* demoData; // This is the XML document loaded from the embedded file "demo table data.xml"
ScopedPointer<XmlElement> demoData; // This is the XML document loaded from the embedded file "demo table data.xml"
XmlElement* columnList; // A pointer to the sub-node of demoData that contains the list of columns XmlElement* columnList; // A pointer to the sub-node of demoData that contains the list of columns
XmlElement* dataList; // A pointer to the sub-node of demoData that contains the list of data rows XmlElement* dataList; // A pointer to the sub-node of demoData that contains the list of data rows
int numRows; // The number of rows of data we've got int numRows; // The number of rows of data we've got
@@ -220,28 +216,27 @@ private:
: owner (owner_) : owner (owner_)
{ {
// just put a combo box inside this component // just put a combo box inside this component
addAndMakeVisible (comboBox = new ComboBox (String::empty));
comboBox->addItem ("fab", 1);
comboBox->addItem ("groovy", 2);
comboBox->addItem ("hep", 3);
comboBox->addItem ("neat", 4);
comboBox->addItem ("wild", 5);
comboBox->addItem ("swingin", 6);
comboBox->addItem ("mad for it", 7);
addAndMakeVisible (&comboBox);
comboBox.addItem ("fab", 1);
comboBox.addItem ("groovy", 2);
comboBox.addItem ("hep", 3);
comboBox.addItem ("neat", 4);
comboBox.addItem ("wild", 5);
comboBox.addItem ("swingin", 6);
comboBox.addItem ("mad for it", 7);
// when the combo is changed, we'll get a callback. // when the combo is changed, we'll get a callback.
comboBox->addListener (this);
comboBox->setWantsKeyboardFocus (false);
comboBox.addListener (this);
comboBox.setWantsKeyboardFocus (false);
} }
~RatingColumnCustomComponent() ~RatingColumnCustomComponent()
{ {
deleteAllChildren();
} }
void resized() void resized()
{ {
comboBox->setBoundsInset (BorderSize (2));
comboBox.setBoundsInset (BorderSize (2));
} }
// Our demo code will call this when we may need to update our contents // Our demo code will call this when we may need to update our contents
@@ -249,17 +244,17 @@ private:
{ {
row = newRow; row = newRow;
columnId = newColumn; columnId = newColumn;
comboBox->setSelectedId (owner.getRating (row), true);
comboBox.setSelectedId (owner.getRating (row), true);
} }
void comboBoxChanged (ComboBox* /*comboBoxThatHasChanged*/) void comboBoxChanged (ComboBox* /*comboBoxThatHasChanged*/)
{ {
owner.setRating (row, comboBox->getSelectedId());
owner.setRating (row, comboBox.getSelectedId());
} }
private: private:
TableDemoComponent& owner; TableDemoComponent& owner;
ComboBox* comboBox;
ComboBox comboBox;
int row, columnId; int row, columnId;
}; };


+ 47
- 50
extras/juce demo/Source/demos/ThreadingDemo.cpp View File

@@ -213,49 +213,40 @@ class ThreadingDemo : public Component,
public Timer, public Timer,
public ButtonListener public ButtonListener
{ {
bool isUsingPool;
ThreadPool pool;
TextButton* controlButton;
public: public:
//============================================================================== //==============================================================================
ThreadingDemo() ThreadingDemo()
: pool (3)
: pool (3),
controlButton ("Thread type"),
isUsingPool (false)
{ {
isUsingPool = false;
setName ("Multithreading"); setName ("Multithreading");
setOpaque (true); setOpaque (true);
addAndMakeVisible (&controlButton);
controlButton.changeWidthToFitText (20);
controlButton.setTopLeftPosition (20, 20);
controlButton.setTriggeredOnMouseDown (true);
controlButton.setAlwaysOnTop (true);
controlButton.addButtonListener (this);
} }
~ThreadingDemo() ~ThreadingDemo()
{ {
pool.removeAllJobs (true, 2000); pool.removeAllJobs (true, 2000);
deleteAllChildren();
} }
// this gets called when a component is added or removed from a parent component.
void parentHierarchyChanged()
void resetAllBalls()
{ {
// we'll use this as an opportunity to start and stop the threads, so that
// we don't leave them going when the component's not actually visible.
stopTimer(); stopTimer();
pool.removeAllJobs (true, 4000); pool.removeAllJobs (true, 4000);
deleteAllChildren();
addAndMakeVisible (controlButton = new TextButton ("Thread type"));
controlButton->changeWidthToFitText (20);
controlButton->setTopLeftPosition (20, 20);
controlButton->setTriggeredOnMouseDown (true);
controlButton->setAlwaysOnTop (true);
controlButton->addButtonListener (this);
balls.clear();
if (isShowing()) if (isShowing())
{ {
while (getNumChildComponents() < 5)
while (balls.size() < 5)
addABall(); addABall();
startTimer (2000); startTimer (2000);
@@ -270,48 +261,39 @@ public:
void setUsingPool (bool usePool) void setUsingPool (bool usePool)
{ {
isUsingPool = usePool; isUsingPool = usePool;
parentHierarchyChanged(); // resets everything
resetAllBalls();
} }
void addABall() void addABall()
{ {
if (isUsingPool) if (isUsingPool)
{ {
DemoThreadPoolJob* newComp = new DemoThreadPoolJob();
addAndMakeVisible (newComp);
newComp->parentSizeChanged();
DemoThreadPoolJob* newBall = new DemoThreadPoolJob();
balls.add (newBall);
addAndMakeVisible (newBall);
newBall->parentSizeChanged();
pool.addJob (newComp);
pool.addJob (newBall);
} }
else else
{ {
DemoThread* newComp = new DemoThread();
addAndMakeVisible (newComp);
newComp->parentSizeChanged();
DemoThread* newBall = new DemoThread();
balls.add (newBall);
addAndMakeVisible (newBall);
newBall->parentSizeChanged();
} }
} }
void removeABall() void removeABall()
{ {
if (isUsingPool)
if (balls.size() > 0)
{ {
ThreadPoolJob* jobToRemove = pool.getJob (Random::getSystemRandom().nextInt (pool.getNumJobs()));
int indexToRemove = Random::getSystemRandom().nextInt (balls.size());
if (jobToRemove != 0)
{
pool.removeJob (jobToRemove, true, 4000);
delete jobToRemove;
}
}
else
{
if (getNumChildComponents() > 1)
{
Component* ball = getChildComponent (1 + Random::getSystemRandom().nextInt (getNumChildComponents() - 1));
if (isUsingPool)
pool.removeJob (dynamic_cast <DemoThreadPoolJob*> (balls [indexToRemove]), true, 4000);
if (dynamic_cast <Button*> (ball) == 0) // don't delete our button!
delete ball;
}
balls.remove (indexToRemove);
} }
} }
@@ -319,27 +301,42 @@ public:
{ {
if (Random::getSystemRandom().nextBool()) if (Random::getSystemRandom().nextBool())
{ {
if (getNumChildComponents() <= 10)
if (balls.size() <= 10)
addABall(); addABall();
} }
else else
{ {
if (getNumChildComponents() > 3)
if (balls.size() > 3)
removeABall(); removeABall();
} }
} }
void buttonClicked (Button* button)
void buttonClicked (Button*)
{ {
PopupMenu m; PopupMenu m;
m.addItem (1, "Use one thread per ball", true, ! isUsingPool); m.addItem (1, "Use one thread per ball", true, ! isUsingPool);
m.addItem (2, "Use a thread pool", true, isUsingPool); m.addItem (2, "Use a thread pool", true, isUsingPool);
const int res = m.showAt (button);
const int res = m.showAt (&controlButton);
if (res != 0) if (res != 0)
setUsingPool (res == 2); setUsingPool (res == 2);
} }
// this gets called when a component is added or removed from a parent component.
void parentHierarchyChanged()
{
// we'll use this as an opportunity to start and stop the threads, so that
// we don't leave them going when the component's not actually visible.
resetAllBalls();
}
private:
ThreadPool pool;
TextButton controlButton;
bool isUsingPool;
OwnedArray<Component> balls;
}; };


+ 52
- 64
extras/juce demo/Source/demos/TreeViewDemo.cpp View File

@@ -29,10 +29,8 @@
//============================================================================== //==============================================================================
class TreeViewDemoItem : public TreeViewItem class TreeViewDemoItem : public TreeViewItem
{ {
XmlElement* xml;
public: public:
TreeViewDemoItem (XmlElement* const xml_)
TreeViewDemoItem (XmlElement& xml_)
: xml (xml_) : xml (xml_)
{ {
} }
@@ -43,41 +41,34 @@ public:
int getItemWidth() const int getItemWidth() const
{ {
return xml->getIntAttribute ("width", -1);
return xml.getIntAttribute ("width", -1);
} }
const String getUniqueName() const const String getUniqueName() const
{ {
if (xml != 0)
return xml->getTagName();
else
return String::empty;
return xml.getTagName();
} }
bool mightContainSubItems() bool mightContainSubItems()
{ {
return xml != 0
&& xml->getFirstChildElement() != 0;
return xml.getFirstChildElement() != 0;
} }
void paintItem (Graphics& g, int width, int height) void paintItem (Graphics& g, int width, int height)
{ {
if (xml != 0)
{
// if this item is selected, fill it with a background colour..
if (isSelected())
g.fillAll (Colours::blue.withAlpha (0.3f));
// if this item is selected, fill it with a background colour..
if (isSelected())
g.fillAll (Colours::blue.withAlpha (0.3f));
// use a "colour" attribute in the xml tag for this node to set the text colour..
g.setColour (Colour (xml->getStringAttribute ("colour", "ff000000").getHexValue32()));
// use a "colour" attribute in the xml tag for this node to set the text colour..
g.setColour (Colour (xml.getStringAttribute ("colour", "ff000000").getHexValue32()));
g.setFont (height * 0.7f);
g.setFont (height * 0.7f);
// draw the xml element's tag name..
g.drawText (xml->getTagName(),
4, 0, width - 4, height,
Justification::centredLeft, true);
}
// draw the xml element's tag name..
g.drawText (xml.getTagName(),
4, 0, width - 4, height,
Justification::centredLeft, true);
} }
void itemOpennessChanged (bool isNowOpen) void itemOpennessChanged (bool isNowOpen)
@@ -92,12 +83,10 @@ public:
// create and add sub-items to this node of the tree, corresponding to // create and add sub-items to this node of the tree, corresponding to
// each sub-element in the XML.. // each sub-element in the XML..
if (xml != 0)
forEachXmlChildElement (xml, child)
{ {
forEachXmlChildElement (*xml, child)
{
addSubItem (new TreeViewDemoItem (child));
}
jassert (child != 0);
addSubItem (new TreeViewDemoItem (*child));
} }
} }
} }
@@ -113,6 +102,9 @@ public:
{ {
return "TreeView Items"; return "TreeView Items";
} }
private:
XmlElement& xml;
}; };
//============================================================================== //==============================================================================
@@ -120,33 +112,23 @@ class TreeViewDemo : public Component,
public DragAndDropContainer, public DragAndDropContainer,
public ButtonListener public ButtonListener
{ {
XmlElement* treeXml;
TreeViewItem* rootItem;
TreeView* treeView;
FileTreeComponent* fileTreeComp;
DirectoryContentsList* directoryList;
TimeSliceThread thread;
TextButton* typeButton;
public: public:
//============================================================================== //==============================================================================
TreeViewDemo() TreeViewDemo()
: treeView (0), : treeView (0),
rootItem (0),
fileTreeComp (0),
directoryList (0),
thread ("Demo file tree thread")
thread ("Demo file tree thread"),
typeButton ("Type of treeview...")
{ {
setName ("Tree Views"); setName ("Tree Views");
const String treeXmlString (BinaryData::treedemo_xml);
XmlDocument parser (treeXmlString);
treeXml = parser.getDocumentElement();
{
const String treeXmlString (BinaryData::treedemo_xml);
XmlDocument parser (treeXmlString);
treeXml = parser.getDocumentElement();
jassert (treeXml != 0);
}
rootItem = new TreeViewDemoItem (treeXml);
rootItem = new TreeViewDemoItem (*treeXml);
rootItem->setOpen (true); rootItem->setOpen (true);
// find the root of the user's home drive, and set that as our root.. // find the root of the user's home drive, and set that as our root..
@@ -158,21 +140,16 @@ public:
directoryList->setDirectory (folder, true, true); directoryList->setDirectory (folder, true, true);
thread.startThread (3); thread.startThread (3);
addAndMakeVisible (typeButton = new TextButton ("Type of treeview..."));
typeButton->addButtonListener (this);
typeButton->setAlwaysOnTop (true);
typeButton->setTriggeredOnMouseDown (true);
addAndMakeVisible (&typeButton);
typeButton.addButtonListener (this);
typeButton.setAlwaysOnTop (true);
typeButton.setTriggeredOnMouseDown (true);
showCustomTreeView(); showCustomTreeView();
} }
~TreeViewDemo() ~TreeViewDemo()
{ {
deleteAllChildren();
delete rootItem;
delete treeXml;
delete directoryList;
} }
void paint (Graphics& g) void paint (Graphics& g)
@@ -195,14 +172,14 @@ public:
else if (fileTreeComp != 0) else if (fileTreeComp != 0)
fileTreeComp->setBoundsInset (BorderSize (40, 10, 10, 10)); fileTreeComp->setBoundsInset (BorderSize (40, 10, 10, 10));
typeButton->changeWidthToFitText (22);
typeButton->setTopLeftPosition (10, 10);
typeButton.changeWidthToFitText (22);
typeButton.setTopLeftPosition (10, 10);
} }
void showCustomTreeView() void showCustomTreeView()
{ {
deleteAndZero (treeView);
deleteAndZero (fileTreeComp);
treeView = 0;
fileTreeComp = 0;
addAndMakeVisible (treeView = new TreeView()); addAndMakeVisible (treeView = new TreeView());
treeView->setRootItem (rootItem); treeView->setRootItem (rootItem);
@@ -213,11 +190,10 @@ public:
void showFileTreeComp() void showFileTreeComp()
{ {
deleteAndZero (treeView);
deleteAndZero (fileTreeComp);
treeView = 0;
fileTreeComp = 0;
addAndMakeVisible (fileTreeComp = new FileTreeComponent (*directoryList)); addAndMakeVisible (fileTreeComp = new FileTreeComponent (*directoryList));
resized(); resized();
} }
@@ -234,7 +210,7 @@ public:
treeView != 0 ? treeView->areOpenCloseButtonsVisible() treeView != 0 ? treeView->areOpenCloseButtonsVisible()
: fileTreeComp->areOpenCloseButtonsVisible()); : fileTreeComp->areOpenCloseButtonsVisible());
const int r = m.showAt (typeButton);
const int r = m.showAt (&typeButton);
if (r == 1) if (r == 1)
{ {
@@ -261,6 +237,18 @@ public:
} }
juce_UseDebuggingNewOperator juce_UseDebuggingNewOperator
private:
ScopedPointer <XmlElement> treeXml;
ScopedPointer <TreeViewItem> rootItem;
ScopedPointer <TreeView> treeView;
ScopedPointer <FileTreeComponent> fileTreeComp;
ScopedPointer <DirectoryContentsList> directoryList;
TimeSliceThread thread;
TextButton typeButton;
}; };


+ 27
- 27
extras/juce demo/Source/demos/WebBrowserDemo.cpp View File

@@ -36,7 +36,7 @@ class DemoBrowserComponent : public WebBrowserComponent
{ {
public: public:
//============================================================================== //==============================================================================
DemoBrowserComponent (TextEditor* addressTextBox_)
DemoBrowserComponent (TextEditor& addressTextBox_)
: addressTextBox (addressTextBox_) : addressTextBox (addressTextBox_)
{ {
} }
@@ -45,7 +45,7 @@ public:
bool pageAboutToLoad (const String& newURL) bool pageAboutToLoad (const String& newURL)
{ {
// We'll just update our address box to reflect the new location.. // We'll just update our address box to reflect the new location..
addressTextBox->setText (newURL, false);
addressTextBox.setText (newURL, false);
// we could return false here to tell the browser not to go ahead with // we could return false here to tell the browser not to go ahead with
// loading the page. // loading the page.
@@ -56,7 +56,7 @@ public:
juce_UseDebuggingNewOperator juce_UseDebuggingNewOperator
private: private:
TextEditor* addressTextBox;
TextEditor& addressTextBox;
DemoBrowserComponent (DemoBrowserComponent&); DemoBrowserComponent (DemoBrowserComponent&);
DemoBrowserComponent& operator= (const DemoBrowserComponent&); DemoBrowserComponent& operator= (const DemoBrowserComponent&);
@@ -71,24 +71,27 @@ class WebBrowserDemo : public Component,
public: public:
//============================================================================== //==============================================================================
WebBrowserDemo() WebBrowserDemo()
: goButton ("Go", "Go to URL"),
backButton ("<<", "Back"),
forwardButton (">>", "Forward")
{ {
setName ("Web Browser"); setName ("Web Browser");
// Create an address box.. // Create an address box..
addAndMakeVisible (addressTextBox = new TextEditor());
addressTextBox->setTextToShowWhenEmpty ("Enter a web address, e.g. http://www.rawmaterialsoftware.com", Colours::grey);
addressTextBox->addListener (this);
addAndMakeVisible (&addressTextBox);
addressTextBox.setTextToShowWhenEmpty ("Enter a web address, e.g. http://www.rawmaterialsoftware.com", Colours::grey);
addressTextBox.addListener (this);
// create the actual browser component // create the actual browser component
addAndMakeVisible (webView = new DemoBrowserComponent (addressTextBox)); addAndMakeVisible (webView = new DemoBrowserComponent (addressTextBox));
// add some buttons.. // add some buttons..
addAndMakeVisible (goButton = new TextButton ("Go", "Go to URL"));
goButton->addButtonListener (this);
addAndMakeVisible (backButton = new TextButton ("<<", "Back"));
backButton->addButtonListener (this);
addAndMakeVisible (forwardButton = new TextButton (">>", "Forward"));
forwardButton->addButtonListener (this);
addAndMakeVisible (&goButton);
goButton.addButtonListener (this);
addAndMakeVisible (&backButton);
backButton.addButtonListener (this);
addAndMakeVisible (&forwardButton);
forwardButton.addButtonListener (this);
// send the browser to a start page.. // send the browser to a start page..
webView->goToURL ("http://www.google.com"); webView->goToURL ("http://www.google.com");
@@ -96,16 +99,15 @@ public:
~WebBrowserDemo() ~WebBrowserDemo()
{ {
deleteAllChildren();
} }
void resized() void resized()
{ {
webView->setBounds (10, 45, getWidth() - 20, getHeight() - 55); webView->setBounds (10, 45, getWidth() - 20, getHeight() - 55);
goButton->setBounds (getWidth() - 45, 10, 35, 25);
addressTextBox->setBounds (100, 10, getWidth() - 155, 25);
backButton->setBounds (10, 10, 35, 25);
forwardButton->setBounds (55, 10, 35, 25);
goButton.setBounds (getWidth() - 45, 10, 35, 25);
addressTextBox.setBounds (100, 10, getWidth() - 155, 25);
backButton.setBounds (10, 10, 35, 25);
forwardButton.setBounds (55, 10, 35, 25);
} }
void textEditorTextChanged (TextEditor&) {} void textEditorTextChanged (TextEditor&) {}
@@ -114,28 +116,26 @@ public:
void textEditorReturnKeyPressed (TextEditor&) void textEditorReturnKeyPressed (TextEditor&)
{ {
webView->goToURL (addressTextBox->getText());
webView->goToURL (addressTextBox.getText());
} }
void buttonClicked (Button* b) void buttonClicked (Button* b)
{ {
if (b == backButton)
if (b == &backButton)
webView->goBack(); webView->goBack();
else if (b == forwardButton)
else if (b == &forwardButton)
webView->goForward(); webView->goForward();
else if (b == goButton)
webView->goToURL (addressTextBox->getText());
else if (b == &goButton)
webView->goToURL (addressTextBox.getText());
} }
juce_UseDebuggingNewOperator juce_UseDebuggingNewOperator
private: private:
DemoBrowserComponent* webView;
ScopedPointer<DemoBrowserComponent> webView;
TextEditor* addressTextBox;
TextButton* goButton;
TextButton* backButton;
TextButton* forwardButton;
TextEditor addressTextBox;
TextButton goButton, backButton, forwardButton;
}; };


+ 129
- 133
extras/juce demo/Source/demos/WidgetsDemo.cpp View File

@@ -30,9 +30,6 @@
class BouncingBallComponent : public Component, class BouncingBallComponent : public Component,
public Timer public Timer
{ {
Colour colour;
float x, y, dx, dy;
public: public:
BouncingBallComponent() BouncingBallComponent()
{ {
@@ -86,14 +83,15 @@ public:
{ {
return false; return false;
} }
private:
Colour colour;
float x, y, dx, dy;
}; };
//============================================================================== //==============================================================================
class DragOntoDesktopDemoComp : public Component class DragOntoDesktopDemoComp : public Component
{ {
Component* parent;
ComponentDragger dragger;
public: public:
DragOntoDesktopDemoComp (Component* p) DragOntoDesktopDemoComp (Component* p)
: parent (p) : parent (p)
@@ -101,13 +99,12 @@ public:
// show off semi-transparency if it's supported by the current OS. // show off semi-transparency if it's supported by the current OS.
setOpaque (! Desktop::canUseSemiTransparentWindows()); setOpaque (! Desktop::canUseSemiTransparentWindows());
for (int i = 3; --i >= 0;)
addAndMakeVisible (new BouncingBallComponent());
for (int i = 0; i < numElementsInArray (balls); ++i)
addAndMakeVisible (&(balls[i]));
} }
~DragOntoDesktopDemoComp() ~DragOntoDesktopDemoComp()
{ {
deleteAllChildren();
} }
void mouseDown (const MouseEvent&) void mouseDown (const MouseEvent&)
@@ -117,9 +114,9 @@ public:
void mouseDrag (const MouseEvent& e) void mouseDrag (const MouseEvent& e)
{ {
if (! parent->isValidComponent())
if (parent == 0)
{ {
delete this;
delete this; // If our parent has been deleted, we'll just get rid of this component
} }
else else
{ {
@@ -159,14 +156,18 @@ public:
g.drawRect (0, 0, getWidth(), getHeight()); g.drawRect (0, 0, getWidth(), getHeight());
} }
private:
Component::SafePointer<Component> parent; // A safe-pointer will become zero if the component that it refers to is deleted..
ComponentDragger dragger;
BouncingBallComponent balls[3];
}; };
//============================================================================== //==============================================================================
class CustomMenuComponent : public PopupMenuCustomComponent, class CustomMenuComponent : public PopupMenuCustomComponent,
public Timer public Timer
{ {
int blobX, blobY;
public: public:
CustomMenuComponent() CustomMenuComponent()
: blobX (0), : blobX (0),
@@ -210,6 +211,9 @@ public:
blobY = Random::getSystemRandom().nextInt (getHeight()); blobY = Random::getSystemRandom().nextInt (getHeight());
repaint(); repaint();
} }
private:
int blobX, blobY;
}; };
//============================================================================== //==============================================================================
@@ -269,7 +273,7 @@ public:
void changeListenerCallback (void* source) void changeListenerCallback (void* source)
{ {
ColourSelector* cs = (ColourSelector*) source;
ColourSelector* cs = static_cast <ColourSelector*> (source);
if (cs->getName() == "text") if (cs->getName() == "text")
setColour (TextButton::textColourOffId, cs->getCurrentColour()); setColour (TextButton::textColourOffId, cs->getCurrentColour());
@@ -279,8 +283,9 @@ public:
}; };
//============================================================================== //==============================================================================
// just a component that deletes all its children, to use for the tabbed pages to avoid
// memory leaks when they're deleted
/* A component to act as a simple container for our demos, which deletes all the child
components that we stuff into it.
*/
class DemoPageComp : public Component class DemoPageComp : public Component
{ {
public: public:
@@ -290,6 +295,12 @@ public:
~DemoPageComp() ~DemoPageComp()
{ {
/* Deleting your child components indiscriminately using deleteAllChildren() is not recommended! It's much
safer to make them embedded members or use ScopedPointers to automatically manage their lifetimes!
In this demo, where we're throwing together a whole bunch of random components, it's simpler to do it
like this, but don't treat this as an example of good practice!
*/
deleteAllChildren(); deleteAllChildren();
} }
}; };
@@ -579,6 +590,12 @@ public:
~ButtonsPage() ~ButtonsPage()
{ {
/* Deleting your child components indiscriminately using deleteAllChildren() is not recommended! It's much
safer to make them embedded members or use ScopedPointers to automatically manage their lifetimes!
In this demo, where we're throwing together a whole bunch of random components, it's simpler to do it
like this, but don't treat this as an example of good practice!
*/
deleteAllChildren(); deleteAllChildren();
} }
@@ -648,57 +665,57 @@ class ToolbarDemoComp : public Component,
{ {
public: public:
ToolbarDemoComp() ToolbarDemoComp()
: depthLabel (String::empty, "Toolbar depth:"),
infoLabel (String::empty, "As well as showing off toolbars, this demo illustrates how to store "
"a set of SVG files in a Zip file, embed that in your application, and read "
"them back in at runtime.\n\nThe icon images here are taken from the open-source "
"Tango icon project."),
orientationButton ("Vertical/Horizontal"),
customiseButton ("Customise...")
{ {
// Create and add the toolbar... // Create and add the toolbar...
addAndMakeVisible (toolbar = new Toolbar());
addAndMakeVisible (&toolbar);
// And use our item factory to add a set of default icons to it... // And use our item factory to add a set of default icons to it...
toolbar->addDefaultItems (factory);
toolbar.addDefaultItems (factory);
// Now we'll just create the other sliders and buttons on the demo page, which adjust // Now we'll just create the other sliders and buttons on the demo page, which adjust
// the toolbar's properties... // the toolbar's properties...
Label* info = new Label (String::empty,
"As well as showing off toolbars, this demo illustrates how to store "
"a set of SVG files in a Zip file, embed that in your application, and read "
"them back in at runtime.\n\nThe icon images here are taken from the open-source "
"Tango icon project.");
addAndMakeVisible (info);
info->setJustificationType (Justification::topLeft);
info->setBounds (80, 80, 450, 100);
info->setInterceptsMouseClicks (false, false);
addAndMakeVisible (depthSlider = new Slider ("toolbar depth:"));
depthSlider->setRange (10.0, 200.0, 1.0);
depthSlider->setValue (50, false);
depthSlider->setSliderStyle (Slider::LinearHorizontal);
depthSlider->setTextBoxStyle (Slider::TextBoxLeft, false, 80, 20);
depthSlider->addListener (this);
depthSlider->setBounds (80, 210, 300, 22);
(new Label (depthSlider->getName(), depthSlider->getName()))->attachToComponent (depthSlider, false);
addAndMakeVisible (orientationButton = new TextButton ("vertical/horizontal"));
orientationButton->addButtonListener (this);
orientationButton->changeWidthToFitText (22);
orientationButton->setTopLeftPosition (depthSlider->getX(), depthSlider->getBottom() + 20);
addAndMakeVisible (customiseButton = new TextButton ("customise..."));
customiseButton->addButtonListener (this);
customiseButton->changeWidthToFitText (22);
customiseButton->setTopLeftPosition (orientationButton->getRight() + 20, orientationButton->getY());
addAndMakeVisible (&infoLabel);
infoLabel.setJustificationType (Justification::topLeft);
infoLabel.setBounds (80, 80, 450, 100);
infoLabel.setInterceptsMouseClicks (false, false);
addAndMakeVisible (&depthSlider);
depthSlider.setRange (10.0, 200.0, 1.0);
depthSlider.setValue (50, false);
depthSlider.setSliderStyle (Slider::LinearHorizontal);
depthSlider.setTextBoxStyle (Slider::TextBoxLeft, false, 80, 20);
depthSlider.addListener (this);
depthSlider.setBounds (80, 210, 300, 22);
depthLabel.attachToComponent (&depthSlider, false);
addAndMakeVisible (&orientationButton);
orientationButton.addButtonListener (this);
orientationButton.changeWidthToFitText (22);
orientationButton.setTopLeftPosition (depthSlider.getX(), depthSlider.getBottom() + 20);
addAndMakeVisible (&customiseButton);
customiseButton.addButtonListener (this);
customiseButton.changeWidthToFitText (22);
customiseButton.setTopLeftPosition (orientationButton.getRight() + 20, orientationButton.getY());
} }
~ToolbarDemoComp() ~ToolbarDemoComp()
{ {
deleteAllChildren();
} }
void resized() void resized()
{ {
if (toolbar->isVertical())
toolbar->setBounds (0, 0, (int) depthSlider->getValue(), getHeight());
if (toolbar.isVertical())
toolbar.setBounds (0, 0, (int) depthSlider.getValue(), getHeight());
else else
toolbar->setBounds (0, 0, getWidth(), (int) depthSlider->getValue());
toolbar.setBounds (0, 0, getWidth(), (int) depthSlider.getValue());
} }
void sliderValueChanged (Slider*) void sliderValueChanged (Slider*)
@@ -708,22 +725,22 @@ public:
void buttonClicked (Button* button) void buttonClicked (Button* button)
{ {
if (button == orientationButton)
if (button == &orientationButton)
{ {
toolbar->setVertical (! toolbar->isVertical());
toolbar.setVertical (! toolbar.isVertical());
resized(); resized();
} }
else if (button == customiseButton)
else if (button == &customiseButton)
{ {
toolbar->showCustomisationDialog (factory);
toolbar.showCustomisationDialog (factory);
} }
} }
private: private:
Toolbar* toolbar;
Slider* depthSlider;
TextButton* orientationButton;
TextButton* customiseButton;
Toolbar toolbar;
Slider depthSlider;
Label depthLabel, infoLabel;
TextButton orientationButton, customiseButton;
//============================================================================== //==============================================================================
class DemoToolbarItemFactory : public ToolbarItemFactory class DemoToolbarItemFactory : public ToolbarItemFactory
@@ -797,35 +814,16 @@ private:
{ {
switch (itemId) switch (itemId)
{ {
case doc_new:
return createButtonFromZipFileSVG (itemId, "new", "document-new.svg");
case doc_open:
return createButtonFromZipFileSVG (itemId, "open", "document-open.svg");
case doc_save:
return createButtonFromZipFileSVG (itemId, "save", "document-save.svg");
case doc_saveAs:
return createButtonFromZipFileSVG (itemId, "save as", "document-save-as.svg");
case edit_copy:
return createButtonFromZipFileSVG (itemId, "copy", "edit-copy.svg");
case edit_cut:
return createButtonFromZipFileSVG (itemId, "cut", "edit-cut.svg");
case edit_paste:
return createButtonFromZipFileSVG (itemId, "paste", "edit-paste.svg");
case juceLogoButton:
return new ToolbarButton (itemId, "juce!", Drawable::createFromImageData (BinaryData::juce_png, BinaryData::juce_pngSize), 0);
case customComboBox:
return new CustomToolbarComboBox (itemId);
default:
break;
case doc_new: return createButtonFromZipFileSVG (itemId, "new", "document-new.svg");
case doc_open: return createButtonFromZipFileSVG (itemId, "open", "document-open.svg");
case doc_save: return createButtonFromZipFileSVG (itemId, "save", "document-save.svg");
case doc_saveAs: return createButtonFromZipFileSVG (itemId, "save as", "document-save-as.svg");
case edit_copy: return createButtonFromZipFileSVG (itemId, "copy", "edit-copy.svg");
case edit_cut: return createButtonFromZipFileSVG (itemId, "cut", "edit-cut.svg");
case edit_paste: return createButtonFromZipFileSVG (itemId, "paste", "edit-paste.svg");
case juceLogoButton: return new ToolbarButton (itemId, "juce!", Drawable::createFromImageData (BinaryData::juce_png, BinaryData::juce_pngSize), 0);
case customComboBox: return new CustomToolbarComboBox (itemId);
default: break;
} }
return 0; return 0;
@@ -867,20 +865,20 @@ private:
{ {
public: public:
CustomToolbarComboBox (const int toolbarItemId) CustomToolbarComboBox (const int toolbarItemId)
: ToolbarItemComponent (toolbarItemId, "Custom Toolbar Item", false)
: ToolbarItemComponent (toolbarItemId, "Custom Toolbar Item", false),
comboBox ("demo toolbar combo box")
{ {
addAndMakeVisible (comboBox = new ComboBox ("demo toolbar combo box"));
addAndMakeVisible (&comboBox);
for (int i = 1; i < 20; ++i) for (int i = 1; i < 20; ++i)
comboBox->addItem ("Toolbar ComboBox item " + String (i), i);
comboBox.addItem ("Toolbar ComboBox item " + String (i), i);
comboBox->setSelectedId (1);
comboBox->setEditableText (true);
comboBox.setSelectedId (1);
comboBox.setEditableText (true);
} }
~CustomToolbarComboBox() ~CustomToolbarComboBox()
{ {
delete comboBox;
} }
bool getToolbarItemSizes (int /*toolbarDepth*/, bool isToolbarVertical, bool getToolbarItemSizes (int /*toolbarDepth*/, bool isToolbarVertical,
@@ -901,14 +899,14 @@ private:
void contentAreaChanged (const Rectangle<int>& contentArea) void contentAreaChanged (const Rectangle<int>& contentArea)
{ {
comboBox->setSize (contentArea.getWidth() - 2,
jmin (contentArea.getHeight() - 2, 22));
comboBox.setSize (contentArea.getWidth() - 2,
jmin (contentArea.getHeight() - 2, 22));
comboBox->setCentrePosition (contentArea.getCentreX(), contentArea.getCentreY());
comboBox.setCentrePosition (contentArea.getCentreX(), contentArea.getCentreY());
} }
private: private:
ComboBox* comboBox;
ComboBox comboBox;
}; };
}; };
@@ -1117,59 +1115,52 @@ const int numGroups = 4;
class WidgetsDemo : public Component, class WidgetsDemo : public Component,
public ButtonListener public ButtonListener
{ {
TextButton* menuButton;
ToggleButton* enableButton;
DemoTabbedComponent* tabs;
public: public:
//============================================================================== //==============================================================================
WidgetsDemo() WidgetsDemo()
: menuButton ("click for a popup menu..",
"click for a demo of the different types of item you can put into a popup menu..."),
enableButton ("enable/disable components")
{ {
setName ("Widgets"); setName ("Widgets");
addAndMakeVisible (tabs = new DemoTabbedComponent());
addAndMakeVisible (&tabs);
//============================================================================== //==============================================================================
menuButton = new TextButton ("click for a popup menu..",
"click for a demo of the different types of item you can put into a popup menu...");
addAndMakeVisible (menuButton);
menuButton->setBounds (10, 10, 200, 24);
menuButton->addButtonListener (this);
menuButton->setTriggeredOnMouseDown (true); // because this button pops up a menu, this lets us
addAndMakeVisible (&menuButton);
menuButton.setBounds (10, 10, 200, 24);
menuButton.addButtonListener (this);
menuButton.setTriggeredOnMouseDown (true); // because this button pops up a menu, this lets us
// hold down the button and drag straight onto the menu // hold down the button and drag straight onto the menu
//============================================================================== //==============================================================================
enableButton = new ToggleButton ("enable/disable components");
addAndMakeVisible (enableButton);
enableButton->setBounds (230, 10, 180, 24);
enableButton->setTooltip ("toggle button");
enableButton->setToggleState (true, false);
enableButton->addButtonListener (this);
addAndMakeVisible (&enableButton);
enableButton.setBounds (230, 10, 180, 24);
enableButton.setTooltip ("toggle button");
enableButton.setToggleState (true, false);
enableButton.addButtonListener (this);
} }
~WidgetsDemo() ~WidgetsDemo()
{ {
deleteAllChildren();
} }
void resized() void resized()
{ {
tabs->setBounds (10, 40, getWidth() - 20, getHeight() - 50);
tabs.setBounds (10, 40, getWidth() - 20, getHeight() - 50);
} }
//============================================================================== //==============================================================================
void buttonClicked (Button* button) void buttonClicked (Button* button)
{ {
if (button == enableButton)
if (button == &enableButton)
{ {
const bool enabled = enableButton->getToggleState();
const bool enabled = enableButton.getToggleState();
menuButton->setEnabled (enabled);
tabs->setEnabled (enabled);
menuButton.setEnabled (enabled);
tabs.setEnabled (enabled);
} }
else if (button == menuButton)
else if (button == &menuButton)
{ {
PopupMenu m; PopupMenu m;
m.addItem (1, "Normal item"); m.addItem (1, "Normal item");
@@ -1182,10 +1173,10 @@ public:
m.addSeparator(); m.addSeparator();
PopupMenu tabsMenu; PopupMenu tabsMenu;
tabsMenu.addItem (1001, "Show tabs at the top", true, tabs->getOrientation() == TabbedButtonBar::TabsAtTop);
tabsMenu.addItem (1002, "Show tabs at the bottom", true, tabs->getOrientation() == TabbedButtonBar::TabsAtBottom);
tabsMenu.addItem (1003, "Show tabs at the left", true, tabs->getOrientation() == TabbedButtonBar::TabsAtLeft);
tabsMenu.addItem (1004, "Show tabs at the right", true, tabs->getOrientation() == TabbedButtonBar::TabsAtRight);
tabsMenu.addItem (1001, "Show tabs at the top", true, tabs.getOrientation() == TabbedButtonBar::TabsAtTop);
tabsMenu.addItem (1002, "Show tabs at the bottom", true, tabs.getOrientation() == TabbedButtonBar::TabsAtBottom);
tabsMenu.addItem (1003, "Show tabs at the left", true, tabs.getOrientation() == TabbedButtonBar::TabsAtLeft);
tabsMenu.addItem (1004, "Show tabs at the right", true, tabs.getOrientation() == TabbedButtonBar::TabsAtRight);
m.addSubMenu ("Tab position", tabsMenu); m.addSubMenu ("Tab position", tabsMenu);
m.addSeparator(); m.addSeparator();
@@ -1238,7 +1229,7 @@ public:
m.addSubMenu ("File chooser dialogs", fileChoosers); m.addSubMenu ("File chooser dialogs", fileChoosers);
int result = m.showAt (menuButton);
int result = m.showAt (&menuButton);
if (result != 0) if (result != 0)
{ {
@@ -1414,23 +1405,28 @@ public:
} }
else if (result == 1001) else if (result == 1001)
{ {
tabs->setOrientation (TabbedButtonBar::TabsAtTop);
tabs.setOrientation (TabbedButtonBar::TabsAtTop);
} }
else if (result == 1002) else if (result == 1002)
{ {
tabs->setOrientation (TabbedButtonBar::TabsAtBottom);
tabs.setOrientation (TabbedButtonBar::TabsAtBottom);
} }
else if (result == 1003) else if (result == 1003)
{ {
tabs->setOrientation (TabbedButtonBar::TabsAtLeft);
tabs.setOrientation (TabbedButtonBar::TabsAtLeft);
} }
else if (result == 1004) else if (result == 1004)
{ {
tabs->setOrientation (TabbedButtonBar::TabsAtRight);
tabs.setOrientation (TabbedButtonBar::TabsAtRight);
} }
} }
} }
} }
private:
TextButton menuButton;
ToggleButton enableButton;
DemoTabbedComponent tabs;
}; };


Loading…
Cancel
Save