code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "gtest/gtest.h"
#include "MockDiagnostics.h"
#include "MockDirectiveHandler.h"
#include "Preprocessor.h"
#ifndef PREPROCESSOR_TESTS_PREPROCESSOR_TEST_H_
#define PREPROCESSOR_TESTS_PREPROCESSOR_TEST_H_
class PreprocessorTest : public testing::Test
{
protected:
PreprocessorTest() : mPreprocessor(&mDiagnostics, &mDirectiveHandler) { }
// Preprocesses the input string and verifies that it matches
// expected output.
void preprocess(const char* input, const char* expected);
MockDiagnostics mDiagnostics;
MockDirectiveHandler mDirectiveHandler;
pp::Preprocessor mPreprocessor;
};
#endif // PREPROCESSOR_TESTS_PREPROCESSOR_TEST_H_
| 010smithzhang-ddd | tests/preprocessor_tests/PreprocessorTest.h | C++ | bsd | 856 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "PreprocessorTest.h"
#include "Token.h"
class IfTest : public PreprocessorTest
{
};
TEST_F(IfTest, If_0)
{
const char* str = "pass_1\n"
"#if 0\n"
"fail\n"
"#endif\n"
"pass_2\n";
const char* expected = "pass_1\n"
"\n"
"\n"
"\n"
"pass_2\n";
preprocess(str, expected);
}
TEST_F(IfTest, If_1)
{
const char* str = "pass_1\n"
"#if 1\n"
"pass_2\n"
"#endif\n"
"pass_3\n";
const char* expected = "pass_1\n"
"\n"
"pass_2\n"
"\n"
"pass_3\n";
preprocess(str, expected);
}
TEST_F(IfTest, If_0_Else)
{
const char* str = "pass_1\n"
"#if 0\n"
"fail\n"
"#else\n"
"pass_2\n"
"#endif\n"
"pass_3\n";
const char* expected = "pass_1\n"
"\n"
"\n"
"\n"
"pass_2\n"
"\n"
"pass_3\n";
preprocess(str, expected);
}
TEST_F(IfTest, If_1_Else)
{
const char* str = "pass_1\n"
"#if 1\n"
"pass_2\n"
"#else\n"
"fail\n"
"#endif\n"
"pass_3\n";
const char* expected = "pass_1\n"
"\n"
"pass_2\n"
"\n"
"\n"
"\n"
"pass_3\n";
preprocess(str, expected);
}
TEST_F(IfTest, If_0_Elif)
{
const char* str = "pass_1\n"
"#if 0\n"
"fail_1\n"
"#elif 0\n"
"fail_2\n"
"#elif 1\n"
"pass_2\n"
"#elif 1\n"
"fail_3\n"
"#else\n"
"fail_4\n"
"#endif\n"
"pass_3\n";
const char* expected = "pass_1\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"pass_2\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"pass_3\n";
preprocess(str, expected);
}
TEST_F(IfTest, If_1_Elif)
{
const char* str = "pass_1\n"
"#if 1\n"
"pass_2\n"
"#elif 0\n"
"fail_1\n"
"#elif 1\n"
"fail_2\n"
"#else\n"
"fail_4\n"
"#endif\n"
"pass_3\n";
const char* expected = "pass_1\n"
"\n"
"pass_2\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"pass_3\n";
preprocess(str, expected);
}
TEST_F(IfTest, If_Elif_Else)
{
const char* str = "pass_1\n"
"#if 0\n"
"fail_1\n"
"#elif 0\n"
"fail_2\n"
"#elif 0\n"
"fail_3\n"
"#else\n"
"pass_2\n"
"#endif\n"
"pass_3\n";
const char* expected = "pass_1\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"pass_2\n"
"\n"
"pass_3\n";
preprocess(str, expected);
}
TEST_F(IfTest, If_0_Nested)
{
const char* str = "pass_1\n"
"#if 0\n"
"fail_1\n"
"#if 1\n"
"fail_2\n"
"#else\n"
"fail_3\n"
"#endif\n"
"#else\n"
"pass_2\n"
"#endif\n"
"pass_3\n";
const char* expected = "pass_1\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"pass_2\n"
"\n"
"pass_3\n";
preprocess(str, expected);
}
TEST_F(IfTest, If_1_Nested)
{
const char* str = "pass_1\n"
"#if 1\n"
"pass_2\n"
"#if 1\n"
"pass_3\n"
"#else\n"
"fail_1\n"
"#endif\n"
"#else\n"
"fail_2\n"
"#endif\n"
"pass_4\n";
const char* expected = "pass_1\n"
"\n"
"pass_2\n"
"\n"
"pass_3\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"pass_4\n";
preprocess(str, expected);
}
TEST_F(IfTest, OperatorPrecedence)
{
const char* str = "#if 1 + 2 * 3 + - (26 % 17 - + 4 / 2)\n"
"fail_1\n"
"#else\n"
"pass_1\n"
"#endif\n";
const char* expected = "\n"
"\n"
"\n"
"pass_1\n"
"\n";
preprocess(str, expected);
}
TEST_F(IfTest, OperatorDefined)
{
const char* str = "#if defined foo\n"
"fail_1\n"
"#else\n"
"pass_1\n"
"#endif\n"
"#define foo\n"
"#if defined(foo)\n"
"pass_2\n"
"#else\n"
"fail_2\n"
"#endif\n"
"#undef foo\n"
"#if defined ( foo ) \n"
"fail_3\n"
"#else\n"
"pass_3\n"
"#endif\n";
const char* expected = "\n"
"\n"
"\n"
"pass_1\n"
"\n"
"\n"
"\n"
"pass_2\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"pass_3\n"
"\n";
preprocess(str, expected);
}
TEST_F(IfTest, OperatorEQ)
{
const char* str = "#if 4 - 1 == 2 + 1\n"
"pass\n"
"#else\n"
"fail\n"
"#endif\n";
const char* expected = "\n"
"pass\n"
"\n"
"\n"
"\n";
preprocess(str, expected);
}
TEST_F(IfTest, OperatorNE)
{
const char* str = "#if 1 != 2\n"
"pass\n"
"#else\n"
"fail\n"
"#endif\n";
const char* expected = "\n"
"pass\n"
"\n"
"\n"
"\n";
preprocess(str, expected);
}
TEST_F(IfTest, OperatorLess)
{
const char* str = "#if 1 < 2\n"
"pass\n"
"#else\n"
"fail\n"
"#endif\n";
const char* expected = "\n"
"pass\n"
"\n"
"\n"
"\n";
preprocess(str, expected);
}
TEST_F(IfTest, OperatorGreater)
{
const char* str = "#if 2 > 1\n"
"pass\n"
"#else\n"
"fail\n"
"#endif\n";
const char* expected = "\n"
"pass\n"
"\n"
"\n"
"\n";
preprocess(str, expected);
}
TEST_F(IfTest, OperatorLE)
{
const char* str = "#if 1 <= 2\n"
"pass_1\n"
"#else\n"
"fail_1\n"
"#endif\n"
"#if 2 <= 2\n"
"pass_2\n"
"#else\n"
"fail_2\n"
"#endif\n";
const char* expected = "\n"
"pass_1\n"
"\n"
"\n"
"\n"
"\n"
"pass_2\n"
"\n"
"\n"
"\n";
preprocess(str, expected);
}
TEST_F(IfTest, OperatorGE)
{
const char* str = "#if 2 >= 1\n"
"pass_1\n"
"#else\n"
"fail_1\n"
"#endif\n"
"#if 2 >= 2\n"
"pass_2\n"
"#else\n"
"fail_2\n"
"#endif\n";
const char* expected = "\n"
"pass_1\n"
"\n"
"\n"
"\n"
"\n"
"pass_2\n"
"\n"
"\n"
"\n";
preprocess(str, expected);
}
TEST_F(IfTest, OperatorBitwiseOR)
{
const char* str = "#if (0xaaaaaaaa | 0x55555555) == 0xffffffff\n"
"pass\n"
"#else\n"
"fail\n"
"#endif\n";
const char* expected = "\n"
"pass\n"
"\n"
"\n"
"\n";
preprocess(str, expected);
}
TEST_F(IfTest, OperatorBitwiseAND)
{
const char* str = "#if (0xaaaaaaa & 0x5555555) == 0\n"
"pass\n"
"#else\n"
"fail\n"
"#endif\n";
const char* expected = "\n"
"pass\n"
"\n"
"\n"
"\n";
preprocess(str, expected);
}
TEST_F(IfTest, OperatorBitwiseXOR)
{
const char* str = "#if (0xaaaaaaa ^ 0x5555555) == 0xfffffff\n"
"pass\n"
"#else\n"
"fail\n"
"#endif\n";
const char* expected = "\n"
"pass\n"
"\n"
"\n"
"\n";
preprocess(str, expected);
}
TEST_F(IfTest, OperatorBitwiseComplement)
{
const char* str = "#if (~ 0xdeadbeef) == -3735928560\n"
"pass\n"
"#else\n"
"fail\n"
"#endif\n";
const char* expected = "\n"
"pass\n"
"\n"
"\n"
"\n";
preprocess(str, expected);
}
TEST_F(IfTest, OperatorLeft)
{
const char* str = "#if (1 << 12) == 4096\n"
"pass\n"
"#else\n"
"fail\n"
"#endif\n";
const char* expected = "\n"
"pass\n"
"\n"
"\n"
"\n";
preprocess(str, expected);
}
TEST_F(IfTest, OperatorRight)
{
const char* str = "#if (31762 >> 8) == 124\n"
"pass\n"
"#else\n"
"fail\n"
"#endif\n";
const char* expected = "\n"
"pass\n"
"\n"
"\n"
"\n";
preprocess(str, expected);
}
TEST_F(IfTest, ExpressionWithMacros)
{
const char* str = "#define one 1\n"
"#define two 2\n"
"#define three 3\n"
"#if one + two == three\n"
"pass\n"
"#else\n"
"fail\n"
"#endif\n";
const char* expected = "\n"
"\n"
"\n"
"\n"
"pass\n"
"\n"
"\n"
"\n";
preprocess(str, expected);
}
TEST_F(IfTest, JunkInsideExcludedBlockIgnored)
{
const char* str = "#if 0\n"
"foo !@#$%^&* .1bar\n"
"#foo\n"
"#if bar\n"
"fail\n"
"#endif\n"
"#else\n"
"pass\n"
"#endif\n";
const char* expected = "\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"pass\n"
"\n";
preprocess(str, expected);
}
TEST_F(IfTest, Ifdef)
{
const char* str = "#define foo\n"
"#ifdef foo\n"
"pass_1\n"
"#else\n"
"fail_1\n"
"#endif\n"
"#undef foo\n"
"#ifdef foo\n"
"fail_2\n"
"#else\n"
"pass_2\n"
"#endif\n";
const char* expected = "\n"
"\n"
"pass_1\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"pass_2\n"
"\n";
preprocess(str, expected);
}
TEST_F(IfTest, Ifndef)
{
const char* str = "#define foo\n"
"#ifndef foo\n"
"fail_1\n"
"#else\n"
"pass_1\n"
"#endif\n"
"#undef foo\n"
"#ifndef foo\n"
"pass_2\n"
"#else\n"
"fail_2\n"
"#endif\n";
const char* expected = "\n"
"\n"
"\n"
"\n"
"pass_1\n"
"\n"
"\n"
"\n"
"pass_2\n"
"\n"
"\n"
"\n";
preprocess(str, expected);
}
TEST_F(IfTest, MissingExpression)
{
const char* str = "#if\n"
"#endif\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::INVALID_EXPRESSION,
pp::SourceLocation(0, 1),
"syntax error"));
pp::Token token;
mPreprocessor.lex(&token);
}
TEST_F(IfTest, DivisionByZero)
{
const char* str = "#if 1 / (3 - (1 + 2))\n"
"#endif\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::DIVISION_BY_ZERO,
pp::SourceLocation(0, 1), "1 / 0"));
pp::Token token;
mPreprocessor.lex(&token);
}
TEST_F(IfTest, ModuloByZero)
{
const char* str = "#if 1 % (3 - (1 + 2))\n"
"#endif\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::DIVISION_BY_ZERO,
pp::SourceLocation(0, 1), "1 % 0"));
pp::Token token;
mPreprocessor.lex(&token);
}
TEST_F(IfTest, DecIntegerOverflow)
{
const char* str = "#if 4294967296\n"
"#endif\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::INTEGER_OVERFLOW,
pp::SourceLocation(0, 1), "4294967296"));
pp::Token token;
mPreprocessor.lex(&token);
}
TEST_F(IfTest, OctIntegerOverflow)
{
const char* str = "#if 077777777777\n"
"#endif\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::INTEGER_OVERFLOW,
pp::SourceLocation(0, 1), "077777777777"));
pp::Token token;
mPreprocessor.lex(&token);
}
TEST_F(IfTest, HexIntegerOverflow)
{
const char* str = "#if 0xfffffffff\n"
"#endif\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::INTEGER_OVERFLOW,
pp::SourceLocation(0, 1), "0xfffffffff"));
pp::Token token;
mPreprocessor.lex(&token);
}
TEST_F(IfTest, UndefinedMacro)
{
const char* str = "#if UNDEFINED\n"
"#endif\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::INVALID_EXPRESSION,
pp::SourceLocation(0, 1),
"syntax error"));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::CONDITIONAL_UNEXPECTED_TOKEN,
pp::SourceLocation(0, 1),
"UNDEFINED"));
pp::Token token;
mPreprocessor.lex(&token);
}
TEST_F(IfTest, InvalidExpressionIgnoredForExcludedElif)
{
const char* str = "#if 1\n"
"pass\n"
"#elif UNDEFINED\n"
"fail\n"
"#endif\n";
const char* expected = "\n"
"pass\n"
"\n"
"\n"
"\n";
// No error or warning.
using testing::_;
EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);
preprocess(str, expected);
}
TEST_F(IfTest, ElseWithoutIf)
{
const char* str = "#else\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::CONDITIONAL_ELSE_WITHOUT_IF,
pp::SourceLocation(0, 1),
"else"));
pp::Token token;
mPreprocessor.lex(&token);
}
TEST_F(IfTest, ElifWithoutIf)
{
const char* str = "#elif 1\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::CONDITIONAL_ELIF_WITHOUT_IF,
pp::SourceLocation(0, 1),
"elif"));
pp::Token token;
mPreprocessor.lex(&token);
}
TEST_F(IfTest, EndifWithoutIf)
{
const char* str = "#endif\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::CONDITIONAL_ENDIF_WITHOUT_IF,
pp::SourceLocation(0, 1),
"endif"));
pp::Token token;
mPreprocessor.lex(&token);
}
TEST_F(IfTest, ElseAfterElse)
{
const char* str = "#if 1\n"
"#else\n"
"#else\n"
"#endif\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::CONDITIONAL_ELSE_AFTER_ELSE,
pp::SourceLocation(0, 3),
"else"));
pp::Token token;
mPreprocessor.lex(&token);
}
TEST_F(IfTest, ElifAfterElse)
{
const char* str = "#if 1\n"
"#else\n"
"#elif 0\n"
"#endif\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::CONDITIONAL_ELIF_AFTER_ELSE,
pp::SourceLocation(0, 3),
"elif"));
pp::Token token;
mPreprocessor.lex(&token);
}
TEST_F(IfTest, UnterminatedIf)
{
const char* str = "#if 1\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::CONDITIONAL_UNTERMINATED,
pp::SourceLocation(0, 1),
"if"));
pp::Token token;
mPreprocessor.lex(&token);
}
TEST_F(IfTest, UnterminatedIfdef)
{
const char* str = "#ifdef foo\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, 0));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::CONDITIONAL_UNTERMINATED,
pp::SourceLocation(0, 1),
"ifdef"));
pp::Token token;
mPreprocessor.lex(&token);
}
| 010smithzhang-ddd | tests/preprocessor_tests/if_test.cpp | C++ | bsd | 22,698 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "PreprocessorTest.h"
#include "Token.h"
class ErrorTest : public PreprocessorTest
{
};
TEST_F(ErrorTest, Empty)
{
const char* str = "#error\n";
const char* expected = "\n";
using testing::_;
EXPECT_CALL(mDirectiveHandler, handleError(pp::SourceLocation(0, 1), ""));
// No error or warning.
EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);
preprocess(str, expected);
}
TEST_F(ErrorTest, OneTokenMessage)
{
const char* str = "#error foo\n";
const char* expected = "\n";
using testing::_;
EXPECT_CALL(mDirectiveHandler,
handleError(pp::SourceLocation(0, 1), " foo"));
// No error or warning.
EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);
preprocess(str, expected);
}
TEST_F(ErrorTest, TwoTokenMessage)
{
const char* str = "#error foo bar\n";
const char* expected = "\n";
using testing::_;
EXPECT_CALL(mDirectiveHandler,
handleError(pp::SourceLocation(0, 1), " foo bar"));
// No error or warning.
EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);
preprocess(str, expected);
}
TEST_F(ErrorTest, Comments)
{
const char* str = "/*foo*/"
"#"
"/*foo*/"
"error"
"/*foo*/"
"foo"
"/*foo*/"
"bar"
"/*foo*/"
"//foo"
"\n";
const char* expected = "\n";
using testing::_;
EXPECT_CALL(mDirectiveHandler,
handleError(pp::SourceLocation(0, 1), " foo bar"));
// No error or warning.
EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);
preprocess(str, expected);
}
TEST_F(ErrorTest, MissingNewline)
{
const char* str = "#error foo";
const char* expected = "";
using testing::_;
// Directive successfully parsed.
EXPECT_CALL(mDirectiveHandler,
handleError(pp::SourceLocation(0, 1), " foo"));
// Error reported about EOF.
EXPECT_CALL(mDiagnostics, print(pp::Diagnostics::EOF_IN_DIRECTIVE, _, _));
preprocess(str, expected);
}
| 010smithzhang-ddd | tests/preprocessor_tests/error_test.cpp | C++ | bsd | 2,347 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "PreprocessorTest.h"
#include "Token.h"
class VersionTest : public PreprocessorTest
{
};
TEST_F(VersionTest, Valid)
{
const char* str = "#version 200\n";
const char* expected = "\n";
using testing::_;
EXPECT_CALL(mDirectiveHandler,
handleVersion(pp::SourceLocation(0, 1), 200));
// No error or warning.
EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);
preprocess(str, expected);
}
TEST_F(VersionTest, CommentsIgnored)
{
const char* str = "/*foo*/"
"#"
"/*foo*/"
"version"
"/*foo*/"
"200"
"/*foo*/"
"//foo"
"\n";
const char* expected = "\n";
using testing::_;
EXPECT_CALL(mDirectiveHandler,
handleVersion(pp::SourceLocation(0, 1), 200));
// No error or warning.
EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);
preprocess(str, expected);
}
TEST_F(VersionTest, MissingNewline)
{
const char* str = "#version 200";
const char* expected = "";
using testing::_;
// Directive successfully parsed.
EXPECT_CALL(mDirectiveHandler,
handleVersion(pp::SourceLocation(0, 1), 200));
// Error reported about EOF.
EXPECT_CALL(mDiagnostics, print(pp::Diagnostics::EOF_IN_DIRECTIVE, _, _));
preprocess(str, expected);
}
TEST_F(VersionTest, AfterComments)
{
const char* str = "/* block comment acceptable */\n"
"// line comment acceptable\n"
"#version 200\n";
const char* expected = "\n\n\n";
using testing::_;
// Directive successfully parsed.
EXPECT_CALL(mDirectiveHandler,
handleVersion(pp::SourceLocation(0, 3), 200));
// No error or warning.
EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);
preprocess(str, expected);
}
TEST_F(VersionTest, AfterWhitespace)
{
const char* str = "\n"
"\n"
"#version 200\n";
const char* expected = "\n\n\n";
using testing::_;
// Directive successfully parsed.
EXPECT_CALL(mDirectiveHandler,
handleVersion(pp::SourceLocation(0, 3), 200));
// No error or warning.
EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);
preprocess(str, expected);
}
TEST_F(VersionTest, AfterValidToken)
{
const char* str = "foo\n"
"#version 200\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, NULL));
using testing::_;
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::VERSION_NOT_FIRST_STATEMENT,
pp::SourceLocation(0, 2), _));
pp::Token token;
do
{
mPreprocessor.lex(&token);
} while (token.type != pp::Token::LAST);
}
TEST_F(VersionTest, AfterInvalidToken)
{
const char* str = "$\n"
"#version 200\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, NULL));
using testing::_;
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::INVALID_CHARACTER,
pp::SourceLocation(0, 1), "$"));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::VERSION_NOT_FIRST_STATEMENT,
pp::SourceLocation(0, 2), _));
pp::Token token;
do
{
mPreprocessor.lex(&token);
} while (token.type != pp::Token::LAST);
}
TEST_F(VersionTest, AfterValidDirective)
{
const char* str = "#\n"
"#version 200\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, NULL));
using testing::_;
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::VERSION_NOT_FIRST_STATEMENT,
pp::SourceLocation(0, 2), _));
pp::Token token;
do
{
mPreprocessor.lex(&token);
} while (token.type != pp::Token::LAST);
}
TEST_F(VersionTest, AfterInvalidDirective)
{
const char* str = "#foo\n"
"#version 200\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, NULL));
using testing::_;
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::DIRECTIVE_INVALID_NAME,
pp::SourceLocation(0, 1), "foo"));
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::VERSION_NOT_FIRST_STATEMENT,
pp::SourceLocation(0, 2), _));
pp::Token token;
do
{
mPreprocessor.lex(&token);
} while (token.type != pp::Token::LAST);
}
TEST_F(VersionTest, AfterExcludedBlock)
{
const char* str = "#if 0\n"
"foo\n"
"#endif\n"
"#version 200\n";
ASSERT_TRUE(mPreprocessor.init(1, &str, NULL));
using testing::_;
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::VERSION_NOT_FIRST_STATEMENT,
pp::SourceLocation(0, 4), _));
pp::Token token;
do
{
mPreprocessor.lex(&token);
} while (token.type != pp::Token::LAST);
}
struct VersionTestParam
{
const char* str;
pp::Diagnostics::ID id;
};
class InvalidVersionTest : public VersionTest,
public testing::WithParamInterface<VersionTestParam>
{
};
TEST_P(InvalidVersionTest, Identified)
{
VersionTestParam param = GetParam();
const char* expected = "\n";
using testing::_;
// No handleVersion call.
EXPECT_CALL(mDirectiveHandler, handleVersion(_, _)).Times(0);
// Invalid version directive call.
EXPECT_CALL(mDiagnostics, print(param.id, pp::SourceLocation(0, 1), _));
preprocess(param.str, expected);
}
static const VersionTestParam kParams[] = {
{"#version\n", pp::Diagnostics::INVALID_VERSION_DIRECTIVE},
{"#version foo\n", pp::Diagnostics::INVALID_VERSION_NUMBER},
{"#version 100 foo\n", pp::Diagnostics::UNEXPECTED_TOKEN},
{"#version 0xffffffff\n", pp::Diagnostics::INTEGER_OVERFLOW}
};
INSTANTIATE_TEST_CASE_P(All, InvalidVersionTest, testing::ValuesIn(kParams));
| 010smithzhang-ddd | tests/preprocessor_tests/version_test.cpp | C++ | bsd | 6,199 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "PreprocessorTest.h"
#include "Input.h"
#include "Token.h"
class InitTest : public PreprocessorTest
{
};
TEST_F(InitTest, NegativeCount)
{
EXPECT_FALSE(mPreprocessor.init(-1, NULL, NULL));
}
TEST_F(InitTest, ZeroCount)
{
EXPECT_TRUE(mPreprocessor.init(0, NULL, NULL));
pp::Token token;
mPreprocessor.lex(&token);
EXPECT_EQ(pp::Token::LAST, token.type);
}
TEST_F(InitTest, NullString)
{
EXPECT_FALSE(mPreprocessor.init(1, NULL, NULL));
}
TEST(InputTest, DefaultConstructor)
{
pp::Input input;
EXPECT_EQ(0, input.count());
EXPECT_EQ(0, input.read(NULL, 1));
}
TEST(InputTest, NullLength)
{
const char* str[] = {"foo"};
pp::Input input(1, str, NULL);
EXPECT_EQ(3, input.length(0));
}
TEST(InputTest, NegativeLength)
{
const char* str[] = {"foo"};
int length[] = {-1};
pp::Input input(1, str, length);
EXPECT_EQ(3, input.length(0));
}
TEST(InputTest, ActualLength)
{
const char* str[] = {"foobar"};
int length[] = {3};
pp::Input input(1, str, length);
// Note that strlen(str[0]) != length[0].
// Even then Input should just accept any non-negative number.
EXPECT_EQ(length[0], input.length(0));
}
TEST(InputTest, String)
{
const char* str[] = {"foo"};
pp::Input input(1, str, NULL);
EXPECT_STREQ(str[0], input.string(0));
}
TEST(InputTest, ReadSingleString)
{
int count = 1;
const char* str[] = {"foo"};
char buf[4] = {'\0', '\0', '\0', '\0'};
int maxSize = 1;
pp::Input input1(count, str, NULL);
EXPECT_EQ(1, input1.read(buf, maxSize));
EXPECT_EQ('f', buf[0]);
EXPECT_EQ(1, input1.read(buf, maxSize));
EXPECT_EQ('o', buf[0]);
EXPECT_EQ(1, input1.read(buf, maxSize));
EXPECT_EQ('o', buf[0]);
EXPECT_EQ(0, input1.read(buf, maxSize));
maxSize = 2;
pp::Input input2(count, str, NULL);
EXPECT_EQ(2, input2.read(buf, maxSize));
EXPECT_STREQ("fo", buf);
EXPECT_EQ(1, input2.read(buf, maxSize));
EXPECT_EQ('o', buf[0]);
EXPECT_EQ(0, input2.read(buf, maxSize));
maxSize = 3;
pp::Input input3(count, str, NULL);
EXPECT_EQ(3, input3.read(buf, maxSize));
EXPECT_STREQ("foo", buf);
EXPECT_EQ(0, input3.read(buf, maxSize));
maxSize = 4;
pp::Input input4(count, str, NULL);
EXPECT_EQ(3, input4.read(buf, maxSize));
EXPECT_STREQ("foo", buf);
EXPECT_EQ(0, input4.read(buf, maxSize));
}
TEST(InputTest, ReadMultipleStrings)
{
int count = 3;
const char* str[] = {"f", "o", "o"};
char buf[4] = {'\0', '\0', '\0', '\0'};
int maxSize = 1;
pp::Input input1(count, str, NULL);
EXPECT_EQ(1, input1.read(buf, maxSize));
EXPECT_EQ('f', buf[0]);
EXPECT_EQ(1, input1.read(buf, maxSize));
EXPECT_EQ('o', buf[0]);
EXPECT_EQ(1, input1.read(buf, maxSize));
EXPECT_EQ('o', buf[0]);
EXPECT_EQ(0, input1.read(buf, maxSize));
maxSize = 2;
pp::Input input2(count, str, NULL);
EXPECT_EQ(2, input2.read(buf, maxSize));
EXPECT_STREQ("fo", buf);
EXPECT_EQ(1, input2.read(buf, maxSize));
EXPECT_EQ('o', buf[0]);
EXPECT_EQ(0, input2.read(buf, maxSize));
maxSize = 3;
pp::Input input3(count, str, NULL);
EXPECT_EQ(3, input3.read(buf, maxSize));
EXPECT_STREQ("foo", buf);
EXPECT_EQ(0, input3.read(buf, maxSize));
maxSize = 4;
pp::Input input4(count, str, NULL);
EXPECT_EQ(3, input4.read(buf, maxSize));
EXPECT_STREQ("foo", buf);
EXPECT_EQ(0, input4.read(buf, maxSize));
}
TEST(InputTest, ReadStringsWithLength)
{
int count = 2;
const char* str[] = {"foo", "bar"};
// Note that the length for the first string is 2 which is less than
// strlen(str[0]. We want to make sure that the last character is ignored.
int length[] = {2, 3};
char buf[6] = {'\0', '\0', '\0', '\0', '\0', '\0'};
int maxSize = 5;
pp::Input input(count, str, length);
EXPECT_EQ(maxSize, input.read(buf, maxSize));
EXPECT_STREQ("fobar", buf);
}
| 010smithzhang-ddd | tests/preprocessor_tests/input_test.cpp | C++ | bsd | 4,150 |
//
// Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "PreprocessorTest.h"
#include "Token.h"
class PragmaTest : public PreprocessorTest
{
};
TEST_F(PragmaTest, EmptyName)
{
const char* str = "#pragma\n";
const char* expected = "\n";
using testing::_;
// No handlePragma calls.
EXPECT_CALL(mDirectiveHandler, handlePragma(_, _, _)).Times(0);
// No error or warning.
EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);
preprocess(str, expected);
}
TEST_F(PragmaTest, EmptyValue)
{
const char* str = "#pragma foo\n";
const char* expected = "\n";
using testing::_;
EXPECT_CALL(mDirectiveHandler,
handlePragma(pp::SourceLocation(0, 1), "foo", ""));
// No error or warning.
EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);
preprocess(str, expected);
}
TEST_F(PragmaTest, NameValue)
{
const char* str = "#pragma foo(bar)\n";
const char* expected = "\n";
using testing::_;
EXPECT_CALL(mDirectiveHandler,
handlePragma(pp::SourceLocation(0, 1), "foo", "bar"));
// No error or warning.
EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);
preprocess(str, expected);
}
TEST_F(PragmaTest, Comments)
{
const char* str = "/*foo*/"
"#"
"/*foo*/"
"pragma"
"/*foo*/"
"foo"
"/*foo*/"
"("
"/*foo*/"
"bar"
"/*foo*/"
")"
"/*foo*/"
"//foo"
"\n";
const char* expected = "\n";
using testing::_;
EXPECT_CALL(mDirectiveHandler,
handlePragma(pp::SourceLocation(0, 1), "foo", "bar"));
// No error or warning.
EXPECT_CALL(mDiagnostics, print(_, _, _)).Times(0);
preprocess(str, expected);
}
TEST_F(PragmaTest, MissingNewline)
{
const char* str = "#pragma foo(bar)";
const char* expected = "";
using testing::_;
// Pragma successfully parsed.
EXPECT_CALL(mDirectiveHandler,
handlePragma(pp::SourceLocation(0, 1), "foo", "bar"));
// Error reported about EOF.
EXPECT_CALL(mDiagnostics, print(pp::Diagnostics::EOF_IN_DIRECTIVE, _, _));
preprocess(str, expected);
}
class InvalidPragmaTest : public PragmaTest,
public testing::WithParamInterface<const char*>
{
};
TEST_P(InvalidPragmaTest, Identified)
{
const char* str = GetParam();
const char* expected = "\n";
using testing::_;
// No handlePragma calls.
EXPECT_CALL(mDirectiveHandler, handlePragma(_, _, _)).Times(0);
// Unrecognized pragma warning.
EXPECT_CALL(mDiagnostics,
print(pp::Diagnostics::UNRECOGNIZED_PRAGMA,
pp::SourceLocation(0, 1), _));
preprocess(str, expected);
}
INSTANTIATE_TEST_CASE_P(All, InvalidPragmaTest, testing::Values(
"#pragma 1\n", // Invalid name.
"#pragma foo()\n", // Missing value.
"#pragma foo bar)\n", // Missing left paren,
"#pragma foo(bar\n", // Missing right paren.
"#pragma foo bar\n", // Missing parens.
"#pragma foo(bar) baz\n")); // Extra tokens.
| 010smithzhang-ddd | tests/preprocessor_tests/pragma_test.cpp | C++ | bsd | 3,455 |
//
// Copyright (c) 2002-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include <sstream>
#include <string>
#include <vector>
#include "GLSLANG/ShaderLang.h"
#include "gtest/gtest.h"
#define SHADER(Src) #Src
class ExpressionLimitTest : public testing::Test {
protected:
static const int kMaxExpressionComplexity = 16;
static const int kMaxCallStackDepth = 16;
static const char* kExpressionTooComplex;
static const char* kCallStackTooDeep;
static const char* kHasRecursion;
virtual void SetUp()
{
memset(&resources, 0, sizeof(resources));
ASSERT_TRUE(ShInitialize() != 0) << "Could not ShInitialize";
GenerateResources(&resources);
}
virtual void TearDown()
{
ASSERT_TRUE(ShFinalize() != 0);
}
// Set up the per compile resources
void GenerateResources(ShBuiltInResources* resources)
{
ShInitBuiltInResources(resources);
resources->MaxVertexAttribs = 8;
resources->MaxVertexUniformVectors = 128;
resources->MaxVaryingVectors = 8;
resources->MaxVertexTextureImageUnits = 0;
resources->MaxCombinedTextureImageUnits = 8;
resources->MaxTextureImageUnits = 8;
resources->MaxFragmentUniformVectors = 16;
resources->MaxDrawBuffers = 1;
resources->OES_standard_derivatives = 0;
resources->OES_EGL_image_external = 0;
resources->MaxExpressionComplexity = kMaxExpressionComplexity;
resources->MaxCallStackDepth = kMaxCallStackDepth;
}
void GenerateLongExpression(int length, std::stringstream* ss)
{
for (int ii = 0; ii < length; ++ii) {
*ss << "+ vec4(" << ii << ")";
}
}
std::string GenerateShaderWithLongExpression(int length)
{
static const char* shaderStart = SHADER(
precision mediump float;
uniform vec4 u_color;
void main()
{
gl_FragColor = u_color
);
std::stringstream ss;
ss << shaderStart;
GenerateLongExpression(length, &ss);
ss << "; }";
return ss.str();
}
std::string GenerateShaderWithUnusedLongExpression(int length)
{
static const char* shaderStart = SHADER(
precision mediump float;
uniform vec4 u_color;
void main()
{
gl_FragColor = u_color;
}
vec4 someFunction() {
return u_color
);
std::stringstream ss;
ss << shaderStart;
GenerateLongExpression(length, &ss);
ss << "; }";
return ss.str();
}
void GenerateDeepFunctionStack(int length, std::stringstream* ss)
{
static const char* shaderStart = SHADER(
precision mediump float;
uniform vec4 u_color;
vec4 function0() {
return u_color;
}
);
*ss << shaderStart;
for (int ii = 0; ii < length; ++ii) {
*ss << "vec4 function" << (ii + 1) << "() {\n"
<< " return function" << ii << "();\n"
<< "}\n";
}
}
std::string GenerateShaderWithDeepFunctionStack(int length)
{
std::stringstream ss;
GenerateDeepFunctionStack(length, &ss);
ss << "void main() {\n"
<< " gl_FragColor = function" << length << "();\n"
<< "}";
return ss.str();
}
std::string GenerateShaderWithUnusedDeepFunctionStack(int length)
{
std::stringstream ss;
GenerateDeepFunctionStack(length, &ss);
ss << "void main() {\n"
<< " gl_FragColor = vec4(0,0,0,0);\n"
<< "}";
return ss.str();
}
// Compiles a shader and if there's an error checks for a specific
// substring in the error log. This way we know the error is specific
// to the issue we are testing.
bool CheckShaderCompilation(ShHandle compiler,
const char* source,
int compileOptions,
const char* expected_error) {
bool success = ShCompile(compiler, &source, 1, compileOptions);
if (success) {
success = !expected_error;
} else {
size_t bufferLen = 0;
ShGetInfo(compiler, SH_INFO_LOG_LENGTH, &bufferLen);
char* buffer(new char [bufferLen]);
ShGetInfoLog(compiler, buffer);
std::string log(buffer, buffer + bufferLen);
delete [] buffer;
if (expected_error)
success = log.find(expected_error) != std::string::npos;
EXPECT_TRUE(success) << log << "\n----shader----\n" << source;
}
return success;
}
ShBuiltInResources resources;
};
const char* ExpressionLimitTest::kExpressionTooComplex =
"Expression too complex";
const char* ExpressionLimitTest::kCallStackTooDeep =
"call stack too deep";
const char* ExpressionLimitTest::kHasRecursion =
"Function recursion detected";
TEST_F(ExpressionLimitTest, ExpressionComplexity)
{
ShShaderSpec spec = SH_WEBGL_SPEC;
ShShaderOutput output = SH_ESSL_OUTPUT;
ShHandle vertexCompiler = ShConstructCompiler(
SH_FRAGMENT_SHADER, spec, output, &resources);
int compileOptions = SH_LIMIT_EXPRESSION_COMPLEXITY;
// Test expression under the limit passes.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler,
GenerateShaderWithLongExpression(
kMaxExpressionComplexity - 10).c_str(),
compileOptions, NULL));
// Test expression over the limit fails.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler,
GenerateShaderWithLongExpression(
kMaxExpressionComplexity + 10).c_str(),
compileOptions, kExpressionTooComplex));
// Test expression over the limit without a limit does not fail.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler,
GenerateShaderWithLongExpression(
kMaxExpressionComplexity + 10).c_str(),
compileOptions & ~SH_LIMIT_EXPRESSION_COMPLEXITY, NULL));
}
TEST_F(ExpressionLimitTest, UnusedExpressionComplexity)
{
ShShaderSpec spec = SH_WEBGL_SPEC;
ShShaderOutput output = SH_ESSL_OUTPUT;
ShHandle vertexCompiler = ShConstructCompiler(
SH_FRAGMENT_SHADER, spec, output, &resources);
int compileOptions = SH_LIMIT_EXPRESSION_COMPLEXITY;
// Test expression under the limit passes.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler,
GenerateShaderWithUnusedLongExpression(
kMaxExpressionComplexity - 10).c_str(),
compileOptions, NULL));
// Test expression over the limit fails.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler,
GenerateShaderWithUnusedLongExpression(
kMaxExpressionComplexity + 10).c_str(),
compileOptions, kExpressionTooComplex));
// Test expression over the limit without a limit does not fail.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler,
GenerateShaderWithUnusedLongExpression(
kMaxExpressionComplexity + 10).c_str(),
compileOptions & ~SH_LIMIT_EXPRESSION_COMPLEXITY, NULL));
}
TEST_F(ExpressionLimitTest, CallStackDepth)
{
ShShaderSpec spec = SH_WEBGL_SPEC;
ShShaderOutput output = SH_ESSL_OUTPUT;
ShHandle vertexCompiler = ShConstructCompiler(
SH_FRAGMENT_SHADER, spec, output, &resources);
int compileOptions = SH_LIMIT_CALL_STACK_DEPTH;
// Test call stack under the limit passes.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler,
GenerateShaderWithDeepFunctionStack(
kMaxCallStackDepth - 10).c_str(),
compileOptions, NULL));
// Test call stack over the limit fails.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler,
GenerateShaderWithDeepFunctionStack(
kMaxCallStackDepth + 10).c_str(),
compileOptions, kCallStackTooDeep));
// Test call stack over the limit without limit does not fail.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler,
GenerateShaderWithDeepFunctionStack(
kMaxCallStackDepth + 10).c_str(),
compileOptions & ~SH_LIMIT_CALL_STACK_DEPTH, NULL));
}
TEST_F(ExpressionLimitTest, UnusedCallStackDepth)
{
ShShaderSpec spec = SH_WEBGL_SPEC;
ShShaderOutput output = SH_ESSL_OUTPUT;
ShHandle vertexCompiler = ShConstructCompiler(
SH_FRAGMENT_SHADER, spec, output, &resources);
int compileOptions = SH_LIMIT_CALL_STACK_DEPTH;
// Test call stack under the limit passes.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler,
GenerateShaderWithUnusedDeepFunctionStack(
kMaxCallStackDepth - 10).c_str(),
compileOptions, NULL));
// Test call stack over the limit fails.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler,
GenerateShaderWithUnusedDeepFunctionStack(
kMaxCallStackDepth + 10).c_str(),
compileOptions, kCallStackTooDeep));
// Test call stack over the limit without limit does not fail.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler,
GenerateShaderWithUnusedDeepFunctionStack(
kMaxCallStackDepth + 10).c_str(),
compileOptions & ~SH_LIMIT_CALL_STACK_DEPTH, NULL));
}
TEST_F(ExpressionLimitTest, Recursion)
{
ShShaderSpec spec = SH_WEBGL_SPEC;
ShShaderOutput output = SH_ESSL_OUTPUT;
ShHandle vertexCompiler = ShConstructCompiler(
SH_FRAGMENT_SHADER, spec, output, &resources);
int compileOptions = 0;
static const char* shaderWithRecursion0 = SHADER(
precision mediump float;
uniform vec4 u_color;
vec4 someFunc() {
return someFunc();
}
void main() {
gl_FragColor = u_color * someFunc();
}
);
static const char* shaderWithRecursion1 = SHADER(
precision mediump float;
uniform vec4 u_color;
vec4 someFunc();
vec4 someFunc1() {
return someFunc();
}
vec4 someFunc() {
return someFunc1();
}
void main() {
gl_FragColor = u_color * someFunc();
}
);
static const char* shaderWithRecursion2 = SHADER(
precision mediump float;
uniform vec4 u_color;
vec4 someFunc() {
if (u_color.x > 0.5) {
return someFunc();
} else {
return vec4(1);
}
}
void main() {
gl_FragColor = someFunc();
}
);
static const char* shaderWithRecursion3 = SHADER(
precision mediump float;
uniform vec4 u_color;
vec4 someFunc() {
if (u_color.x > 0.5) {
return vec4(1);
} else {
return someFunc();
}
}
void main() {
gl_FragColor = someFunc();
}
);
static const char* shaderWithRecursion4 = SHADER(
precision mediump float;
uniform vec4 u_color;
vec4 someFunc() {
return (u_color.x > 0.5) ? vec4(1) : someFunc();
}
void main() {
gl_FragColor = someFunc();
}
);
static const char* shaderWithRecursion5 = SHADER(
precision mediump float;
uniform vec4 u_color;
vec4 someFunc() {
return (u_color.x > 0.5) ? someFunc() : vec4(1);
}
void main() {
gl_FragColor = someFunc();
}
);
static const char* shaderWithRecursion6 = SHADER(
precision mediump float;
uniform vec4 u_color;
vec4 someFunc() {
return someFunc();
}
void main() {
gl_FragColor = u_color;
}
);
static const char* shaderWithNoRecursion = SHADER(
precision mediump float;
uniform vec4 u_color;
vec3 rgb(int r, int g, int b) {
return vec3(float(r) / 255.0, float(g) / 255.0, float(b) / 255.0);
}
// these external calls used to incorrectly trigger
// recursion detection.
vec3 hairColor0 = rgb(151, 200, 234);
vec3 faceColor2 = rgb(183, 148, 133);
void main() {
gl_FragColor = u_color + vec4(hairColor0 + faceColor2, 0);
}
);
static const char* shaderWithRecursion7 = SHADER(
precision mediump float;
uniform vec4 u_color;
vec4 function2() {
return u_color;
}
vec4 function1() {
vec4 a = function2();
vec4 b = function1();
return a + b;
}
void main() {
gl_FragColor = function1();
}
);
static const char* shaderWithRecursion8 = SHADER(
precision mediump float;
uniform vec4 u_color;
vec4 function1();
vec4 function3() {
return function1();
}
vec4 function2() {
return function3();
}
vec4 function1() {
return function2();
}
void main() {
gl_FragColor = function1();
}
);
// Check simple recursions fails.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler, shaderWithRecursion0,
compileOptions, kHasRecursion));
// Check simple recursions fails.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler, shaderWithRecursion1,
compileOptions, kHasRecursion));
// Check if recursions fails.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler, shaderWithRecursion2,
compileOptions, kHasRecursion));
// Check if recursions fails.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler, shaderWithRecursion3,
compileOptions, kHasRecursion));
// Check ternary recursions fails.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler, shaderWithRecursion4,
compileOptions, kHasRecursion));
// Check ternary recursions fails.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler, shaderWithRecursion5,
compileOptions, kHasRecursion));
// Check unused recursions passes.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler, shaderWithRecursion6,
compileOptions, NULL));
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler, shaderWithRecursion7,
compileOptions, kHasRecursion));
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler, shaderWithRecursion8,
compileOptions, kHasRecursion));
// Check unused recursions fails if limiting call stack
// since we check all paths.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler, shaderWithRecursion6,
compileOptions | SH_LIMIT_CALL_STACK_DEPTH, kHasRecursion));
// Check unused recursions passes.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler, shaderWithNoRecursion,
compileOptions, NULL));
// Check unused recursions passes if limiting call stack.
EXPECT_TRUE(CheckShaderCompilation(
vertexCompiler, shaderWithNoRecursion,
compileOptions | SH_LIMIT_CALL_STACK_DEPTH, NULL));
}
| 010smithzhang-ddd | tests/compiler_tests/ExpressionLimit_test.cpp | C++ | bsd | 15,420 |
//
// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
#include "compiler/VariablePacker.h"
#include "gtest/gtest.h"
TEST(VariablePacking, Pack) {
VariablePacker packer;
TVariableInfoList vars;
const int kMaxRows = 16;
// test no vars.
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
ShDataType types[] = {
SH_FLOAT_MAT4, // 0
SH_FLOAT_MAT2, // 1
SH_FLOAT_VEC4, // 2
SH_INT_VEC4, // 3
SH_BOOL_VEC4, // 4
SH_FLOAT_MAT3, // 5
SH_FLOAT_VEC3, // 6
SH_INT_VEC3, // 7
SH_BOOL_VEC3, // 8
SH_FLOAT_VEC2, // 9
SH_INT_VEC2, // 10
SH_BOOL_VEC2, // 11
SH_FLOAT, // 12
SH_INT, // 13
SH_BOOL, // 14
SH_SAMPLER_2D, // 15
SH_SAMPLER_CUBE, // 16
SH_SAMPLER_EXTERNAL_OES, // 17
SH_SAMPLER_2D_RECT_ARB, // 18
};
for (size_t tt = 0; tt < sizeof(types) / sizeof(types[0]); ++tt) {
ShDataType type = types[tt];
int num_rows = VariablePacker::GetNumRows(type);
int num_components_per_row = VariablePacker::GetNumComponentsPerRow(type);
// Check 1 of the type.
vars.clear();
vars.push_back(TVariableInfo(type, 1));
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
// Check exactly the right amount of 1 type as an array.
int num_vars = kMaxRows / num_rows;
vars.clear();
vars.push_back(TVariableInfo(type, num_vars));
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
// test too many
vars.clear();
vars.push_back(TVariableInfo(type, num_vars + 1));
EXPECT_FALSE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
// Check exactly the right amount of 1 type as individual vars.
num_vars = kMaxRows / num_rows *
((num_components_per_row > 2) ? 1 : (4 / num_components_per_row));
vars.clear();
for (int ii = 0; ii < num_vars; ++ii) {
vars.push_back(TVariableInfo(type, 1));
}
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
// Check 1 too many.
vars.push_back(TVariableInfo( type, 1));
EXPECT_FALSE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
}
// Test example from GLSL ES 3.0 spec chapter 11.
vars.clear();
vars.push_back(TVariableInfo(SH_FLOAT_VEC4, 1));
vars.push_back(TVariableInfo(SH_FLOAT_MAT3, 1));
vars.push_back(TVariableInfo(SH_FLOAT_MAT3, 1));
vars.push_back(TVariableInfo(SH_FLOAT_VEC2, 6));
vars.push_back(TVariableInfo(SH_FLOAT_VEC2, 4));
vars.push_back(TVariableInfo(SH_FLOAT_VEC2, 1));
vars.push_back(TVariableInfo(SH_FLOAT, 3));
vars.push_back(TVariableInfo(SH_FLOAT, 2));
vars.push_back(TVariableInfo(SH_FLOAT, 1));
EXPECT_TRUE(packer.CheckVariablesWithinPackingLimits(kMaxRows, vars));
}
| 010smithzhang-ddd | tests/compiler_tests/VariablePacker_test.cpp | C++ | bsd | 3,080 |
# Copyright (c) 2012 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'targets': [
{
'target_name': 'gtest',
'type': 'static_library',
'include_dirs': [
'../third_party/googletest',
'../third_party/googletest/include',
],
'sources': [
'../third_party/googletest/src/gtest-all.cc',
],
},
{
'target_name': 'gmock',
'type': 'static_library',
'include_dirs': [
'../third_party/googlemock',
'../third_party/googlemock/include',
'../third_party/googletest/include',
],
'sources': [
'../third_party/googlemock/src/gmock-all.cc',
],
},
{
'target_name': 'preprocessor_tests',
'type': 'executable',
'dependencies': [
'../src/build_angle.gyp:preprocessor',
'gtest',
'gmock',
],
'include_dirs': [
'../src/compiler/preprocessor',
'../third_party/googletest/include',
'../third_party/googlemock/include',
],
'sources': [
'../third_party/googlemock/src/gmock_main.cc',
'preprocessor_tests/char_test.cpp',
'preprocessor_tests/comment_test.cpp',
'preprocessor_tests/define_test.cpp',
'preprocessor_tests/error_test.cpp',
'preprocessor_tests/extension_test.cpp',
'preprocessor_tests/identifier_test.cpp',
'preprocessor_tests/if_test.cpp',
'preprocessor_tests/input_test.cpp',
'preprocessor_tests/location_test.cpp',
'preprocessor_tests/MockDiagnostics.h',
'preprocessor_tests/MockDirectiveHandler.h',
'preprocessor_tests/number_test.cpp',
'preprocessor_tests/operator_test.cpp',
'preprocessor_tests/pragma_test.cpp',
'preprocessor_tests/PreprocessorTest.cpp',
'preprocessor_tests/PreprocessorTest.h',
'preprocessor_tests/space_test.cpp',
'preprocessor_tests/token_test.cpp',
'preprocessor_tests/version_test.cpp',
],
},
{
'target_name': 'compiler_tests',
'type': 'executable',
'dependencies': [
'../src/build_angle.gyp:translator_glsl',
'gtest',
'gmock',
],
'include_dirs': [
'../include',
'../src',
'../third_party/googletest/include',
'../third_party/googlemock/include',
],
'sources': [
'../third_party/googlemock/src/gmock_main.cc',
'compiler_tests/ExpressionLimit_test.cpp',
'compiler_tests/VariablePacker_test.cpp',
],
},
],
}
# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
| 010smithzhang-ddd | tests/build_tests.gyp | Python | bsd | 2,776 |
import org.vu.contest.ContestSubmission;
import org.vu.contest.ContestEvaluation;
import java.util.Random;
import java.util.Properties;
import java.util.Arrays;
import java.util.Comparator;
class Crossover {
int geneStart, geneEnd; // the indexes of genes the operator works on, operationStart inclusive, operationEnd exclusive
Crossover(int geneStart, int geneEnd) {
this.geneStart = geneStart;
this.geneEnd = geneEnd;
}
public double[][] cross(double[] individual1, double[] individual2) {
throw new UnsupportedOperationException();
}
}
class ParentSelection {
public int[] selectParents(Individual[] population, int populationSize) {return null;}
public void initSelection(Individual[] population, int populationSize) {}
}
interface ISurvivalSelection {
public void select(Individual[] population, int populationSize);
}
class Mutation {
final boolean evaluatesOffspring; // if the operator evaluates the offspring
Mutation(boolean evaluatesOffspring) {
this.evaluatesOffspring = evaluatesOffspring;
}
public void initGeneration() { };
// If the operator evaluates the offspring,
// it Must evaluate the new individual and return false, it there were no more evaluations
public boolean mutate(Individual individual) {
throw new UnsupportedOperationException();
}
}
interface IInitialisaion {
public void initialise(Individual[] population, int populationSize);
}
class InUniformRandom implements IInitialisaion {
private ContestEvaluation evaluation_;
private Random rnd_;
public InUniformRandom(Random rnd, ContestEvaluation evaluation) {
evaluation_ = evaluation;
rnd_ = rnd;
}
private double[] genomebuff = new double[10];
public void initialise(Individual[] population, int populationSize) {
for (int i = 0; i < populationSize; ++i) {
population[i] = new Individual();
for (int j = 0; j < 10; ++j) {
population[i].genome[j] = rnd_.nextDouble() * 10 - 5;
genomebuff[j] = population[i].genome[j] ;
}
population[i].fitness = (Double) evaluation_.evaluate(genomebuff);
}
}
}
class PSUniformRandom extends ParentSelection {
private Random rnd_;
private boolean allowCloning;
public PSUniformRandom(Random rnd, boolean allowCloning) {
this.allowCloning = allowCloning;
rnd_ = rnd;
}
public int[] selectParents(Individual[] population, int populationSize) {
int[] parents = new int[2];
parents[0] = rnd_.nextInt(populationSize);
parents[1] = rnd_.nextInt(populationSize);
if (!allowCloning) {
while(parents[0] == parents[1])
parents[1] = rnd_.nextInt(populationSize);
}
return parents;
}
}
class PSRouletteWheel extends ParentSelection {
// WARNING: this is slow, do not use on the first test function
private Random rnd_;
double sumFitness;
double minFitness;
private boolean allowCloning;
public PSRouletteWheel(Random rnd, boolean allowCloning) {
rnd_ = rnd;
this.allowCloning = allowCloning;
}
public void initSelection(Individual[] population, int populationSize) {
sumFitness = population[0].fitness;
minFitness = population[0].fitness;
for(int i = 1; i < populationSize; ++i) {
sumFitness += population[i].fitness;
if(minFitness > population[i].fitness)
minFitness = population[i].fitness;
}
sumFitness -= populationSize * minFitness;
}
public int[] selectParents(Individual[] population, int populationSize) {
int[] parents = new int[2];
double draw = rnd_.nextDouble() * sumFitness;
parents[0] = 0;
while (draw > (population[parents[0]].fitness - minFitness)) {
draw = draw - (population[parents[0]].fitness - minFitness);
parents[0]++;
}
draw = rnd_.nextDouble() * sumFitness;
parents[1] = 0;
while (draw > (population[parents[1]].fitness - minFitness)) {
draw = draw - (population[parents[1]].fitness - minFitness);
parents[1]++;
}
if (!allowCloning) {
while(parents[1] == parents[0]) {
draw = rnd_.nextDouble() * sumFitness;
parents[1] = 0;
while (draw > (population[parents[1]].fitness - minFitness)) {
draw = draw - (population[parents[1]].fitness - minFitness);
parents[1]++;
}
}
}
return parents;
}
}
class PSRankBased extends ParentSelection {
private Random rnd_;
private double s, c1, c2;
private boolean allowCloning;
// 1.0 < s <= 2.0, if s is 0.0 then it implements exponential
public PSRankBased(Random rnd, double s, boolean allowCloning) {
rnd_ = rnd;
this.s = s;
this.allowCloning = allowCloning;
}
public void initSelection(Individual[] population, int populationSize) {
Arrays.sort(population, 0, populationSize, new Comparator<Individual>() {
@Override
public int compare(Individual o1, Individual o2) {
return ((Double) o2.fitness).compareTo(o1.fitness);
}
});
if (s == 0.0) {
c1 = populationSize;
for (int i = 0; i<populationSize; ++i) {
c1 -= Math.exp(-i);
}
c1 = 1.0/c1;
c2 = Math.exp(-1);
} else {
c1 = (2.0-s)/populationSize;
c2 = 2.0*(s-1)/((populationSize-1)*populationSize);
}
}
public int[] selectParents(Individual[] population, int populationSize) {
int[] parents = new int[2];
double draw = rnd_.nextDouble();
parents[0] = 0;
if (s == 0.0) {
double prob = c1;
while (draw > c1 - prob) {
draw -= c1 - prob;
prob *= c2;
parents[0]++;
}
} else {
while (draw > (c1 + parents[0]*c2)) {
draw -= c1 + parents[0]*c2;
parents[0]++;
}
}
draw = rnd_.nextDouble();
parents[1] = 0;
if (s == 0.0) {
double prob = c1;
while (draw > c1 - prob) {
draw -= c1 - prob;
prob *= c2;
parents[1]++;
}
} else {
while (draw > (c1 + parents[1]*c2)) {
draw -= c1 + parents[1]*c2;
parents[1]++;
}
}
if (!allowCloning) {
while(parents[1] == parents[0]) {
draw = rnd_.nextDouble();
parents[1] = 0;
if (s == 0.0) {
double prob = c1;
while (draw > c1 - prob) {
draw -= c1 - prob;
prob *= c2;
parents[1]++;
}
} else {
while (draw > (c1 + parents[1]*c2)) {
draw -= c1 + parents[1]*c2;
parents[1]++;
}
}
}
}
parents[0] = populationSize - parents[0] - 1;
parents[1] = populationSize - parents[1] - 1;
return parents;
}
}
class SSAnnihilation implements ISurvivalSelection {
public SSAnnihilation() {}
public void select(Individual[] population, int populationSize) {
for(int i = populationSize; i < population.length; i++) {
population[i - populationSize].copy(population[i]);
}
}
}
class SSRankBased implements ISurvivalSelection {
private Random rnd_;
private double s, c1, c2;
// 1.0 < s <= 2.0, if s is 0.0 then it implements exponential
public SSRankBased(Random rnd, double s) {
rnd_ = rnd;
this.s = s;
}
public void select(Individual[] population, int populationSize) {
Arrays.sort(population, 0, population.length, new Comparator<Individual>() {
@Override
public int compare(Individual o1, Individual o2) {
return ((Double) o2.fitness).compareTo(o1.fitness);
}
});
if (s == 0.0) {
c1 = population.length;
for (int i = 0; i<population.length; ++i) {
c1 -= Math.exp(-i);
}
c1 = 1.0/c1;
c2 = Math.exp(-1);
} else {
c1 = (2.0-s)/population.length;
c2 = 2.0*(s-1)/((population.length-1)*population.length);
}
int selected;
double draw;
for(int i = populationSize; i < population.length; i++) {
draw = rnd_.nextDouble();
selected = 0;
if (s == 0.0) {
double prob = c1;
while (draw > c1 - prob) {
draw -= c1 - prob;
prob *= c2;
selected++;
}
} else {
while (draw > (c1 + selected*c2)) {
draw -= c1 + selected*c2;
selected++;
}
}
population[i - populationSize].copy(population[selected]);
}
}
}
class SSSimpleSort implements ISurvivalSelection {
public SSSimpleSort() {}
public void select(Individual[] population, int populationSize) {
Arrays.sort(population, new Comparator<Individual>() {
@Override
public int compare(Individual o1, Individual o2) {
return ((Double) o2.fitness).compareTo(o1.fitness);
}
});
}
}
class NPointCrossover extends Crossover {
private int N;
private Random rnd_;
public NPointCrossover(Random random, int geneStart, int geneEnd, int N) {
super(geneStart, geneEnd);
this.N = N;
rnd_ = random;
}
public double[][] cross(double[] parent1, double[] parent2) {
if (N > geneEnd - geneStart - 1)
return null;
int[] Xpoints = new int[N];
int numxpoints = 0;
int draw;
int i;
while(numxpoints < N) {
draw = 1 + rnd_.nextInt(geneEnd - geneStart-1);
i = 0;
while (i < numxpoints && Xpoints[i] != draw)
i++;
if (i == numxpoints) {
Xpoints[numxpoints] = draw;
numxpoints++;
}
}
Arrays.sort(Xpoints);
double[][] children = new double[2][geneEnd - geneStart];
boolean flip = false;
numxpoints = 0;
for (i = 0; i < geneEnd - geneStart; ++i) {
if (numxpoints < N && Xpoints[numxpoints] == i) {
numxpoints++;
flip = !flip;
}
if(flip) {
children[0][i] = parent2[geneStart + i];
children[1][i] = parent1[geneStart + i];
} else {
children[0][i] = parent1[geneStart + i];
children[1][i] = parent2[geneStart + i];
}
}
return children;
}
}
class IstvanNFlipCrossover extends Crossover {
private int N;
private Random rnd_;
public IstvanNFlipCrossover(Random random, int geneStart, int geneEnd, int N) {
super(geneStart, geneEnd);
this.N = N;
rnd_ = random;
}
public double[][] cross(double[] parent1, double[] parent2) {
if (N > geneEnd - geneStart)
return null;
int[] Xpoints = new int[N];
int numxpoints = 0;
int draw;
int i;
while(numxpoints < N) {
draw = rnd_.nextInt(geneEnd - geneStart);
i = 0;
while (i < numxpoints && Xpoints[i] != draw)
i++;
if (i == numxpoints) {
Xpoints[numxpoints] = draw;
numxpoints++;
}
}
Arrays.sort(Xpoints);
double[][] children = new double[2][geneEnd - geneStart];
numxpoints = 0;
for (i = 0; i < geneEnd - geneStart; ++i) {
if (numxpoints < N && Xpoints[numxpoints] == i) {
numxpoints++;
children[0][i] = parent2[geneStart+i];
children[1][i] = parent1[geneStart+i];
} else {
children[0][i] = parent1[geneStart+i];
children[1][i] = parent2[geneStart+i];
}
}
return children;
}
}
class RandomFlipCrossover extends Crossover {
private Random rnd_;
public RandomFlipCrossover(Random random, int geneStart, int geneEnd) {
super(geneStart, geneEnd);
rnd_ = random;
}
public double[][] cross(double[] parent1, double[] parent2) {
double[][] children = new double[1][geneEnd - geneStart];
for (int i = 0; i < geneEnd - geneStart; ++i) {
if (rnd_.nextBoolean())
children[0][i] = parent1[geneStart + i];
else
children[0][i] = parent2[geneStart + i];
}
return children;
}
}
class AveragerCrossover extends Crossover {
public AveragerCrossover(int geneStart, int geneEnd) {
super(geneStart, geneEnd);
}
public double[][] cross(double[] parent1, double[] parent2) {
double[][] children = new double[1][geneEnd - geneStart];
for (int i = 0; i < geneEnd - geneStart; ++i) {
children[0][i] = (parent1[geneStart + i] + parent2[geneStart + i]) / 2.0;
}
return children;
}
}
class CompoundCrossover extends Crossover {
private Crossover crossover1;
private Crossover crossover2;
public CompoundCrossover(Crossover crossover1, Crossover crossover2) {
super(crossover1.geneStart, crossover2.geneEnd);
this.crossover1 = crossover1;
this.crossover2 = crossover2;
}
public double[][] cross(double[] parent1, double[] parent2) {
double[][] children1 = crossover1.cross(parent1, parent2);
double[][] children2 = crossover2.cross(parent1, parent2);
int numOffspring;
if (children2.length < children1.length)
numOffspring = children2.length;
else
numOffspring = children1.length;
double[][] children = new double[numOffspring][geneEnd-geneStart];
for (int i = 0; i < crossover1.geneEnd - geneStart; ++i) {
for (int j = 0; j < numOffspring; ++j) {
children[j][i] = children1[j][i];
}
}
for(int i = 0; i < geneEnd - crossover2.geneStart; ++i) {
for (int j = 0; j < numOffspring; ++j) {
children[j][i+crossover1.geneEnd] = children2[j][i];
}
}
return children;
}
}
class UniformMutation extends Mutation {
private double flip_prob;
private Random rnd_;
public UniformMutation(Random random, double prob) {
super(false);
flip_prob = prob;
rnd_ = random;
}
public boolean mutate(Individual individual) {
for(int i = 0; i < individual.genome.length; ++i){
if (flip_prob > rnd_.nextDouble()) {
individual.genome[i] = rnd_.nextDouble()*10.0 - 5.0;
}
}
return true;
}
}
class GaussianMutation extends Mutation {
private double flip_prob;
private Random rnd_;
private double mean;
private double mean_dic;
private ContestEvaluation evaluation_;
public GaussianMutation(Random random, ContestEvaluation evaluation, double prob, double mean) {
this(random, evaluation, prob, mean, 1.0);
}
public GaussianMutation(Random random, ContestEvaluation evaluation, double prob, double mean, double mean_dic) {
super(false);
evaluation_ = evaluation;
flip_prob = prob;
rnd_ = random;
this.mean = mean;
this.mean_dic = mean_dic;
}
public boolean mutate(Individual individual) {
for(int i = 0; i < individual.genome.length; ++i){
if (flip_prob > rnd_.nextDouble()) {
individual.genome[i] = rnd_.nextGaussian()*mean + individual.genome[i];
if (individual.genome[i] > 5)
individual.genome[i] = 5;
else if (individual.genome[i] < -5)
individual.genome[i] = -5;
}
}
return true;
}
public void initGeneration() {
mean *= mean_dic;
}
}
class GaussianMutationWithGlobalControl extends Mutation {
private double flip_prob;
private Random rnd_;
private ContestEvaluation evaluation_;
public GaussianMutationWithGlobalControl(Random random, ContestEvaluation evaluation, double prob) {
super(true);
evaluation_ = evaluation;
flip_prob = prob;
rnd_ = random;
}
private double[] g = new double[10];
private double calGamma(double fitness) {
double coef;
double epsilon = 0.00000000001;
if (10.0 - fitness > 1.0)
coef = Math.sqrt((10.0 - fitness));
else {
coef = (10.0 - fitness)/0.4;
// coef = Math.pow(coef, 1.1);
}
if (coef < epsilon)
coef = epsilon;
return coef;
}
public boolean mutate(Individual individual) {
for (int j = 0; j < 10; ++j) {
g[j] = individual.genome[j];
}
Double fitness = (Double) evaluation_.evaluate(g);
if (fitness == null)
return false;
individual.fitness = fitness.doubleValue();
double gamma = calGamma(individual.fitness);
for(int i = 0; i < 10; ++i){
if (flip_prob > rnd_.nextDouble()) {
individual.genome[i] = rnd_.nextGaussian()*gamma + individual.genome[i];
if (individual.genome[i] > 5)
individual.genome[i] = 5;
else if (individual.genome[i] < -5)
individual.genome[i] = -5;
}
}
for (int j = 0; j < 10; ++j) {
g[j] = individual.genome[j];
}
fitness = (Double) evaluation_.evaluate(g);
if (fitness == null)
return false;
individual.fitness = fitness.doubleValue();
// individual.genome[10] = Math.sqrt(10.0 - individual.fitness);
return true;
}
}
class UncorrelatedWithNSigmas extends Mutation {
private double tau, taucommon, epsilon;
private Random rnd_;
public UncorrelatedWithNSigmas(Random random, double taucommon, double tau, double epsilon) {
super(false);
this.rnd_ = random;
this.taucommon = taucommon;
this.tau = tau;
this.epsilon = epsilon;
}
public boolean mutate(Individual individual) {
double n = Math.exp(taucommon * rnd_.nextGaussian());
for(int j = 10; j < 20; ++j) {
individual.genome[j] = individual.genome[j] * Math.exp(tau * rnd_.nextGaussian()) * n;
if(individual.genome[j] < epsilon)
individual.genome[j] = epsilon;
}
for(int j = 0; j < 10; ++j){
individual.genome[j] += individual.genome[j+10] * rnd_.nextGaussian();
if (individual.genome[j] > 5)
individual.genome[j] = 5;
else if (individual.genome[j] < -5)
individual.genome[j] = -5;
}
return true;
}
}
class Individual {
public double[] genome;
public double fitness;
public int successfulMutations = 0;
public Individual() {
fitness = 100;
genome = new double[20];
for (int i = 10; i < genome.length; ++i) {
genome[i] = 1;
}
}
public void copy(Individual other) {
genome = other.genome.clone();
fitness = other.fitness;
}
}
public class player19 implements ContestSubmission
{
private Random rnd_;
private ContestEvaluation evaluation_;
private int evaluations_limit_;
private Mutation mutation_;
private Crossover crossover_;
private ParentSelection parentSelection_;
private ISurvivalSelection survivalSelection_;
private IInitialisaion initialisation_;
private boolean isMultimodal;
private boolean hasStructure;
private boolean isSeparable;
public static void main(String[] args) {
int runs = 10;
double result = 0.0;
for (int i = 0; i < runs; ++i) {
ContestEvaluation eval = new SphereEvaluation();
ContestSubmission sub = new player19();
sub.setSeed(System.currentTimeMillis());
sub.setEvaluation(eval);
sub.run();
result += eval.getFinalResult();
}
System.out.println("Result: "+result/runs);
}
public player19()
{
rnd_ = new Random();
}
public void setSeed(long seed)
{
// Set seed of algorithms random process
rnd_.setSeed(seed);
}
public void setEvaluation(ContestEvaluation evaluation)
{
// Set evaluation problem used in the run
evaluation_ = evaluation;
// Get evaluation properties
Properties props = evaluation.getProperties();
evaluations_limit_ = Integer.parseInt(props.getProperty("Evaluations"));
isMultimodal = Boolean.parseBoolean(props.getProperty("Multimodal"));
hasStructure = Boolean.parseBoolean(props.getProperty("GlobalStructure"));
isSeparable = Boolean.parseBoolean(props.getProperty("Separable"));
if(isMultimodal){
// Do sth
}else{
// Do sth else
}
}
private void method(int num) {
switch (num) {
case 1:
initialisation_ = new InUniformRandom(rnd_, evaluation_);
parentSelection_ = new PSUniformRandom(rnd_, false);
crossover_ = new NPointCrossover(rnd_, 0, 10, 3);
mutation_ = new UniformMutation(rnd_, 0.1);
survivalSelection_ = new SSSimpleSort();
break;
case 2:
initialisation_ = new InUniformRandom(rnd_, evaluation_);
parentSelection_ = new PSUniformRandom(rnd_, false);
crossover_ = new NPointCrossover(rnd_, 0, 10, 3);
mutation_ = new UniformMutation(rnd_, 0.7);
survivalSelection_ = new SSAnnihilation();
break;
case 3:
initialisation_ = new InUniformRandom(rnd_, evaluation_);
parentSelection_ = new PSUniformRandom(rnd_, false);
crossover_ = new IstvanNFlipCrossover(rnd_, 0, 10, 3);
mutation_ = new UniformMutation(rnd_, 0.1);
survivalSelection_ = new SSSimpleSort();
break;
case 4:
initialisation_ = new InUniformRandom(rnd_, evaluation_);
parentSelection_ = new PSUniformRandom(rnd_, false);
crossover_ = new IstvanNFlipCrossover(rnd_, 0, 10, 3);
mutation_ = new GaussianMutation(rnd_, evaluation_, 0.09, 2);
survivalSelection_ = new SSSimpleSort();
break;
case 5:
initialisation_ = new InUniformRandom(rnd_, evaluation_);
parentSelection_ = new PSRouletteWheel(rnd_, false);
crossover_ = new IstvanNFlipCrossover(rnd_, 0, 10, 2);
mutation_ = new GaussianMutation(rnd_, evaluation_, 0.3, 1);
survivalSelection_ = new SSAnnihilation();
break;
case 6:
initialisation_ = new InUniformRandom(rnd_, evaluation_);
parentSelection_ = new PSRouletteWheel(rnd_, false);
crossover_ = new IstvanNFlipCrossover(rnd_, 0, 10, 2);
mutation_ = new GaussianMutation(rnd_, evaluation_, 0.29, 0.9);
survivalSelection_ = new SSAnnihilation();
break;
case 7:
initialisation_ = new InUniformRandom(rnd_, evaluation_);
parentSelection_ = new PSRankBased(rnd_, 1.9, true);
crossover_ = new IstvanNFlipCrossover(rnd_, 0, 10, 4);
mutation_ = new GaussianMutation(rnd_, evaluation_, 0.1, 0.4);
survivalSelection_ = new SSAnnihilation();
break;
case 8:
initialisation_ = new InUniformRandom(rnd_, evaluation_);
parentSelection_ = new PSRankBased(rnd_, 1.9, true);
crossover_ = new IstvanNFlipCrossover(rnd_, 0, 10, 3);
mutation_ = new GaussianMutation(rnd_, evaluation_, 0.7, 1, 0.91);
survivalSelection_ = new SSAnnihilation();
break;
case 9:
initialisation_ = new InUniformRandom(rnd_, evaluation_);
parentSelection_ = new PSUniformRandom(rnd_, true);
crossover_ = new CompoundCrossover(new RandomFlipCrossover(rnd_, 0, 10),
new AveragerCrossover(10, 20));
mutation_ = new UncorrelatedWithNSigmas(rnd_, 1.0 / Math.sqrt(2*10), 1.0 / Math.sqrt(2 * Math.sqrt(10)), 0.000000001);
survivalSelection_ = new SSSimpleSort();
break;
case 10:
initialisation_ = new InUniformRandom(rnd_, evaluation_);
parentSelection_ = new PSUniformRandom(rnd_, true);
crossover_ = new CompoundCrossover(new IstvanNFlipCrossover(rnd_, 0, 10, 4),
new AveragerCrossover(10, 20));
mutation_ = new GaussianMutationWithGlobalControl(rnd_, evaluation_, 8.0);
survivalSelection_ = new SSSimpleSort();
break;
case 11:
initialisation_ = new InUniformRandom(rnd_, evaluation_);
parentSelection_ = new PSUniformRandom(rnd_, true);
crossover_ = new CompoundCrossover(new RandomFlipCrossover(rnd_, 0, 10),
new AveragerCrossover(10, 20));
mutation_ = new GaussianMutationWithGlobalControl(rnd_, evaluation_, 8.0);
survivalSelection_ = new SSSimpleSort();
break;
case 12:
initialisation_ = new InUniformRandom(rnd_, evaluation_);
parentSelection_ = new PSUniformRandom(rnd_, true);
// crossover_ = null;
// crossover_ = new AveragerCrossover(0, 10);
crossover_ = new IstvanNFlipCrossover(rnd_, 0, 10, 5);
mutation_ = new GaussianMutationWithGlobalControl(rnd_, evaluation_, 1.0);
survivalSelection_ = new SSSimpleSort();
break;
default:
break;
}
}
public void run()
{
if (isMultimodal) {
// method(7);
method(11);
int populationSize = 15;
int numOffsprings = 60;
Individual[] population = new Individual[populationSize+numOffsprings];
initialisation_ = new InUniformRandom(rnd_, evaluation_);
initialisation_.initialise(population, populationSize);
for (int i = populationSize; i < populationSize + numOffsprings; i++) {
population[i] = new Individual();
}
boolean running = true;
double tau = 1.0 / Math.sqrt(2 * Math.sqrt(10)) * 1.01;
double taucommon = 1.0 / Math.sqrt(2*10) * 1.01;
double epsilon = 0.000000001;
double epsilon2 = 0.0000000001;
int parent1, parent2;
double[] genomebuff = new double[10];
double bestfitness;
while (running) {
bestfitness = -9999999;
for(int i = 0; i<populationSize; ++i) {
if (bestfitness < population[i].fitness)
bestfitness = population[i].fitness;
}
for (int i = populationSize; i < populationSize + numOffsprings; i += 1) {
parent1 = rnd_.nextInt(populationSize);
parent2 = rnd_.nextInt(populationSize);
for (int j = 0; j < 10; ++j) {
double ratio;
double switchlimit = 8.9;
if (population[parent1].fitness == 0.0 && population[parent2].fitness == 0.0)
ratio = 0.5;
else if (population[parent1].fitness > switchlimit && population[parent2].fitness > switchlimit)
ratio = (population[parent1].fitness - switchlimit)
/ (population[parent1].fitness + population[parent2].fitness - 18.0);
else
ratio = population[parent1].fitness
/ (population[parent1].fitness + population[parent2].fitness);
double ratiomin = 0.4;
if (ratio < ratiomin)
ratio = ratiomin;
else if (ratio > 1.0 - ratiomin)
ratio = 1.0 - ratiomin;
population[i].genome[j] = population[parent1].genome[j] * ratio
+ population[parent2].genome[j] * (1.0-ratio);
}
for(int j = 10; j < 20; ++j) {
population[i].genome[j] = (population[parent1].genome[j] + population[parent2].genome[j]) / 2.0;
}
}
for (int i = populationSize; i < populationSize+ numOffsprings; ++i) {
// GAMMA MUTATION
double n = Math.exp(taucommon * rnd_.nextGaussian());
for(int j = 10; j < 20; ++j) {
population[i].genome[j] = population[i].genome[j] * Math.exp(tau * rnd_.nextGaussian()) * n;
if(population[i].genome[j] < epsilon)
population[i].genome[j] = epsilon;
}
// GENOME MUTATION
for(int j = 0; j < 10; ++j){
population[i].genome[j] += population[i].genome[j+10] * rnd_.nextGaussian();
if (population[i].genome[j] > 5)
population[i].genome[j] = 5;
else if (population[i].genome[j] < -5)
population[i].genome[j] = -5;
}
// FITTNESS EVALUATION
for (int j = 0; j < 10; ++j) {
genomebuff[j] = population[i].genome[j];
}
Double fitness = (Double) evaluation_.evaluate(genomebuff);
if (fitness == null || fitness.doubleValue() == 10.0) {
running = false;
break;
}
population[i].fitness = fitness.doubleValue();
if (population[i].fitness < 9.0) {
double sum = 0.0;
for (int j = 10; j < 20; ++j) {
sum += population[i].genome[j] * population[i].genome[j];
}
sum = Math.sqrt(sum);
double coef;
if (9.0 > population[i].fitness) {
coef = (10.0 - population[i].fitness) / 6;
coef = Math.pow(coef, 1.1);
} else {
coef = (10.0 - population[i].fitness);
coef = Math.pow(coef, 0.3);
}
if (coef < epsilon2)
coef = epsilon2;
coef /= sum;
for (int j = 10; j < 20; ++j) {
population[i].genome[j] *= coef;
}
}
}
Arrays.sort(population, new Comparator<Individual>() {
@Override
public int compare(Individual o1, Individual o2) {
return ((Double) o2.fitness).compareTo(o1.fitness);
}
});
}
int remain = 0;
while (evaluation_.evaluate(genomebuff) != null)
remain++;
System.out.println("Remaining evals: " + String.valueOf(remain));
if (true) return;
} else {
method(12);
int populationSize = 15;
int numOffsprings = 60;
Individual[] population = new Individual[populationSize+numOffsprings];
initialisation_ = new InUniformRandom(rnd_, evaluation_);
initialisation_.initialise(population, populationSize);
for (int i = populationSize; i < populationSize + numOffsprings; i++) {
population[i] = new Individual();
}
boolean running = true;
double tau = 1.0 / Math.sqrt(2 * Math.sqrt(10)) * 1.01;
double taucommon = 1.0 / Math.sqrt(2*10) * 1.01;
double epsilon = 0.000000001;
double epsilon2 = 0.0000000001;
int parent1, parent2;
double[] genomebuff = new double[10];
double bestfitness;
while (running) {
bestfitness = -9999999;
for(int i = 0; i<populationSize; ++i) {
if (bestfitness < population[i].fitness)
bestfitness = population[i].fitness;
}
for (int i = populationSize; i < populationSize + numOffsprings; i += 1) {
parent1 = rnd_.nextInt(populationSize);
parent2 = rnd_.nextInt(populationSize);
for (int j = 0; j < 10; ++j) {
parent1 = rnd_.nextInt(populationSize);
parent2 = rnd_.nextInt(populationSize);
double ratio;
double switchlimit = 8.9;
if (population[parent1].fitness <= 0.0 && population[parent2].fitness <= 0.0)
ratio = 0.5;
else if (population[parent1].fitness > switchlimit && population[parent2].fitness > switchlimit)
ratio = (population[parent1].fitness - switchlimit)
/ (population[parent1].fitness + population[parent2].fitness - 18.0);
else
ratio = population[parent1].fitness
/ (population[parent1].fitness + population[parent2].fitness);
double ratiomin = 0.3;
if (ratio < ratiomin)
ratio = ratiomin;
else if (ratio > 1.0 - ratiomin)
ratio = 1.0 - ratiomin;
population[i].genome[j] = population[parent1].genome[j] * ratio
+ population[parent2].genome[j] * (1.0-ratio);
}
for(int j = 10; j < 20; ++j) {
population[i].genome[j] = (population[parent1].genome[j] + population[parent2].genome[j]) / 2.0;
}
}
for (int i = populationSize; i < populationSize+ numOffsprings; ++i) {
// GAMMA MUTATION
double n = Math.exp(taucommon * rnd_.nextGaussian());
for(int j = 10; j < 20; ++j) {
population[i].genome[j] = population[i].genome[j] * Math.exp(tau * rnd_.nextGaussian()) * n;
if(population[i].genome[j] < epsilon)
population[i].genome[j] = epsilon;
}
// GENOME MUTATION
for(int j = 0; j < 10; ++j){
population[i].genome[j] += population[i].genome[j+10] * rnd_.nextGaussian();
if (population[i].genome[j] > 5)
population[i].genome[j] = 5;
else if (population[i].genome[j] < -5)
population[i].genome[j] = -5;
}
// FITTNESS EVALUATION
for (int j = 0; j < 10; ++j) {
genomebuff[j] = population[i].genome[j];
}
Double fitness = (Double) evaluation_.evaluate(genomebuff);
if (fitness == null || fitness.doubleValue() == 10.0) {
running = false;
break;
}
population[i].fitness = fitness.doubleValue();
if (population[i].fitness < 8.0) {
double sum = 0.0;
for (int j = 10; j < 20; ++j) {
sum += population[i].genome[j] * population[i].genome[j];
}
sum = Math.sqrt(sum);
double coef;
if (9.0 > population[i].fitness) {
coef = (10.0 - population[i].fitness) / 4;
} else {
coef = (10.0 - population[i].fitness);
coef = Math.pow(coef, 0.3);
}
if (coef < epsilon2)
coef = epsilon2;
coef /= sum;
for (int j = 10; j < 20; ++j) {
population[i].genome[j] *= coef;
}
}
}
Arrays.sort(population, new Comparator<Individual>() {
@Override
public int compare(Individual o1, Individual o2) {
return ((Double) o2.fitness).compareTo(o1.fitness);
}
});
}
int remain = 0;
while (evaluation_.evaluate(genomebuff) != null)
remain++;
System.out.println("Remaining evals: " + String.valueOf(remain));
return;
}
int populationSize = 100;
int numOffsprings = 107;
Individual[] population = new Individual[populationSize+numOffsprings];
initialisation_.initialise(population, populationSize);
for (int i = populationSize; i < populationSize + numOffsprings; i++) {
population[i] = new Individual();
}
double bestfitness;
boolean running = true;
double[] g = new double[10];
while (running) {
bestfitness = -9999999;
for(int i = 0; i<populationSize; ++i) {
if (bestfitness < population[i].fitness)
bestfitness = population[i].fitness;
}
parentSelection_.initSelection(population, populationSize);
for(int i = 0; i < numOffsprings;) {
int[] parents = parentSelection_.selectParents(population, populationSize);
if (crossover_ != null) {
double[][] crossed = crossover_.cross(population[parents[0]].genome,
population[parents[1]].genome);
for (int j = 0; j < crossed.length; ++j) {
population[populationSize + i + j].genome = crossed[j];
population[populationSize + i + j].fitness = population[parents[0]].fitness;
}
i += crossed.length;
} else {
population[populationSize + i ].genome = population[parents[0]].genome.clone();
population[populationSize + i ].fitness = population[parents[0]].fitness;
population[populationSize + i + 1].genome = population[parents[1]].genome.clone();
population[populationSize + i + 1].fitness = population[parents[1]].fitness;
i += 2;
}
}
mutation_.initGeneration();
for (int i = populationSize; i < populationSize + numOffsprings; ++i) {
if (mutation_.evaluatesOffspring) {
if (!mutation_.mutate(population[i])) {
running = false;
break;
}
} else {
mutation_.mutate(population[i]);
for (int j = 0; j < 10; ++j) {
g[j] = population[i].genome[j];
}
Double fitness = (Double) evaluation_.evaluate(g);
if (fitness == null) {
running = false;
break;
}
population[i].fitness = fitness.doubleValue();
}
}
survivalSelection_.select(population, populationSize);
}
}
}
| 0c31ae322fa380cbb3bc56181c4c7778 | player19.java | Java | asf20 | 38,699 |
import java.util.Properties;
import org.vu.contest.ContestEvaluation;
// This is an example evalation. It is based on the standard sphere function. It is a maximization problem with a maximum of 10 for
// vector x=0.
// The sphere function itself is for minimization with minimum at 0, thus fitness is calculated as Fitness = 10 - 10*(f-fbest),
// where f is the result of the sphere function
// Base performance is calculated as the distance of the expected fitness of a random search (with the same amount of available
// evaluations) on the sphere function to the function minimum, thus Base = E[f_best_random] - ftarget. Fitness is scaled
// according to this base, thus Fitness = 10 - 10*(f-fbest)/Base
public class SphereEvaluation implements ContestEvaluation
{
// Evaluations budget
private final static int EVALS_LIMIT_ = 10000;
// The base performance. It is derived by doing random search on the sphere function (see function method) with the same
// amount of evaluations
private final static double BASE_ = 11.5356;
// The minimum of the sphere function
private final static double ftarget_=0;
// Best fitness so far
private double best_;
// Evaluations used so far
private int evaluations_;
// Properties of the evaluation
private String multimodal_ = "false";
private String regular_ = "true";
private String separable_ = "true";
private String evals_ = Integer.toString(EVALS_LIMIT_);
public SphereEvaluation()
{
best_ = 0;
evaluations_ = 0;
}
// The standard sphere function. It has one minimum at 0.
private double function(double[] x)
{
double sum = 0;
for(int i=0; i<10; i++) sum += x[i]*x[i];
return sum;
}
@Override
public Object evaluate(Object result)
{
// Check argument
if(!(result instanceof double[])) throw new IllegalArgumentException();
double ind[] = (double[]) result;
if(ind.length!=10) throw new IllegalArgumentException();
if(evaluations_>EVALS_LIMIT_) return null;
// Transform function value (sphere is minimization).
// Normalize using the base performance
double f = 10 - 10*( (function(ind)-ftarget_) / BASE_ ) ;
if(f>best_) best_ = f;
evaluations_++;
return new Double(f);
}
@Override
public Object getData(Object arg0)
{
return null;
}
@Override
public double getFinalResult()
{
return best_;
}
@Override
public Properties getProperties()
{
Properties props = new Properties();
props.put("Multimodal", multimodal_);
props.put("Regular", regular_);
props.put("Separable", separable_);
props.put("Evaluations", evals_);
return props;
}
}
| 0c31ae322fa380cbb3bc56181c4c7778 | SphereEvaluation.java | Java | asf20 | 2,603 |
/****************************************************************************
* Copyright 2009 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.brightprof;
import java.math.BigDecimal;
import android.content.ContentResolver;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.view.Window;
import android.view.WindowManager;
public class Util {
/**
* Calculates the current application-defined brightness value of the phone.
* This is done by taking the actual system brightness (a value from 0 to 255)
* and normalizing it to a scale of 0 to 100. The actual brightness percentage
* is calculated on the scale of minimumBrightness to 255, though.
*
* @param resolver
* The ContentResolver.
* @param db
* A database accessor pointing to a DB with the minimum
* brightness setting in it.
* @return A value between 0 and 100.
*/
static int getPhoneBrighness(ContentResolver resolver, DbAccessor db) {
int systemBrightness = getSystemBrightness(resolver);
int minValue = db.getMinimumBrightness();
// The system brightness can range from 0 to 255. To normalize this
// to the application's 0 to 100 brightness values, we lookup the
// configured minimum value and then normalize for the range
// minValue to 255.
BigDecimal d = new BigDecimal((systemBrightness - minValue)
/ (255.0 - minValue) * 100.0);
d = d.setScale(0, BigDecimal.ROUND_HALF_EVEN);
int normalizedBrightness = d.intValue();
if (normalizedBrightness < 0) {
// This can happen if another application sets the phone's brightness
// to a value lower than our configured minimum.
return 0;
} else {
return normalizedBrightness;
}
}
/**
* Finds the phone's system brightness setting. Returns 0 if there is an error
* getting this setting.
*
* @param resolver
* The ContentResolver.
* @return A value between 0 and 255.
*/
static int getSystemBrightness(ContentResolver resolver) {
// Lookup the initial system brightness.
int systemBrightness = 0;
try {
systemBrightness = Settings.System.getInt(resolver,
Settings.System.SCREEN_BRIGHTNESS);
} catch (SettingNotFoundException e) {
// TODO Log an error message.
}
return systemBrightness;
}
/**
* Sets the brightness for the activity supplied as well as the system
* brightness level. The brightness value passed in should be an integer
* between 0 and 100. This method will translate that number into a normalized
* value using the devices actual maximum brightness level and the minimum
* brightness level calibrated via the CalibrateActivity activity.
*
* @param resolver
* The ContentResolver.
* @param window
* The activity Window.
* @param brightnessPercentage
* An integer between 0 and 100.
*/
static void setPhoneBrightness(ContentResolver resolver,
Window window,
DbAccessor db,
int brightnessPercentage) {
// Lookup the minimum acceptable brightness set by the CalibrationActivity.
int min_value = db.getMinimumBrightness();
// Convert the normalized application brightness to a system value (between
// min_value and 255).
BigDecimal d = new BigDecimal((brightnessPercentage / 100.0)
* (255 - min_value) + min_value);
d = d.setScale(0, BigDecimal.ROUND_HALF_EVEN);
int brightnessUnits = d.intValue();
if (brightnessUnits < min_value) {
brightnessUnits = min_value;
} else if (brightnessUnits > 255) {
brightnessUnits = 255;
}
setSystemBrightness(resolver, brightnessUnits);
setActivityBrightness(window, brightnessUnits);
}
/**
* Sets the phone's global brightness level. This does not change the screen's
* brightness immediately. Valid brightnesses range from 0 to 255.
*
* @param resolver
* The ContentResolver.
* @param brightnessUnits
* An integer between 0 and 255.
*/
static void setSystemBrightness(ContentResolver resolver, int brightnessUnits) {
// Change the system brightness setting. This doesn't change the
// screen brightness immediately. (Scale 0 - 255).
Settings.System.putInt(resolver, Settings.System.SCREEN_BRIGHTNESS, brightnessUnits);
}
/**
* Sets the screen brightness for this activity. The screen brightness will
* change immediately. As soon as the activity terminates, the brightness will
* return to the system brightness. Valid brightnesses range from 0 to 255.
*
* @param window
* The activity window.
* @param brightnessUnits
* An integer between 0 and 255.
*/
static void setActivityBrightness(Window window, int brightnessUnits) {
// Set the brightness of the current window. This takes effect immediately.
// When the window is closed, the new system brightness is used.
// (Scale 0.0 - 1.0).
WindowManager.LayoutParams lp = window.getAttributes();
lp.screenBrightness = brightnessUnits / 255.0f;
window.setAttributes(lp);
}
// These constants are not exposed through the API, but are defined in
// Settings.System:
// http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;f=core/java/android/provider/Settings.java;h=f7e55db80b8849c023152ad06d97040199c4e8c5;hb=HEAD
private static final String SCREEN_BRIGHTNESS_MODE = "screen_brightness_mode";
private static final int SCREEN_BRIGHTNESS_MODE_MANUAL = 0;
private static final int SCREEN_BRIGHTNESS_MODE_AUTOMATIC = 1;
static boolean supportsAutoBrightness(ContentResolver resolver) {
// This is probably not the best way to do this. The actual capability
// is stored in
// com.android.internal.R.bool.config_automatic_brightness_available
// which is not available through the API.
try {
Settings.System.getInt(resolver, SCREEN_BRIGHTNESS_MODE);
return true;
} catch (SettingNotFoundException e) {
return false;
}
}
static boolean getAutoBrightnessEnabled(ContentResolver resolver) {
try {
int autobright = Settings.System.getInt(resolver, SCREEN_BRIGHTNESS_MODE);
return autobright == SCREEN_BRIGHTNESS_MODE_AUTOMATIC;
} catch (SettingNotFoundException e) {
return false;
}
}
static void setAutoBrightnessEnabled(ContentResolver resolver, boolean enabled) {
if (enabled) {
Settings.System.putInt(resolver, SCREEN_BRIGHTNESS_MODE,
SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
} else {
Settings.System.putInt(resolver, SCREEN_BRIGHTNESS_MODE,
SCREEN_BRIGHTNESS_MODE_MANUAL);
}
}
}
| 0indri0-1111 | android/brightnessprof/src/com/angrydoughnuts/android/brightprof/Util.java | Java | asf20 | 7,382 |
/****************************************************************************
* Copyright 2009 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.brightprof;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
public class BrightnessProfiles extends Activity {
private static final int ACTIVITY_EDIT = 0;
private static final int ACTIVITY_CALIBRATE = 1;
private static final int MENU_EDIT = 0;
private static final int MENU_DELETE = 1;
private static final int OPTION_CALIBRATE = 0;
private int appBrightness;
private DbAccessor dbAccessor;
private Cursor listViewCursor;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize the database helper.
dbAccessor = new DbAccessor(this);
setContentView(R.layout.main);
// Button to close the main window.
Button closeBtn = (Button) findViewById(R.id.close_button);
closeBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
finish();
}
});
// Button to open the edit dialog (in add mode).
Button addBtn = (Button) findViewById(R.id.add_button);
addBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplication(), EditActivity.class);
startActivityForResult(i, ACTIVITY_EDIT);
}
});
// Setup auto brightness checkbox handler.
CheckBox checkbox = (CheckBox) findViewById(R.id.auto_brightness);
checkbox.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
public void onCheckedChanged(
CompoundButton buttonView, boolean isChecked) {
Util.setAutoBrightnessEnabled(getContentResolver(), isChecked);
lockBrightnessControls(isChecked);
// Update the app brightness in case auto brightness changed it.
appBrightness = Util.getPhoneBrighness(getContentResolver(), dbAccessor);
setBrightness(appBrightness);
refreshDisplay();
}
});
// Setup slider.
SeekBar slider = (SeekBar) findViewById(R.id.slider);
slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromTouch) {
if (fromTouch) {
setBrightness(progress);
refreshDisplay();
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// Get a database cursor.
listViewCursor = dbAccessor.getAllProfiles();
startManagingCursor(listViewCursor);
// Populate the list view using the Cursor.
String[] from = new String[] { "name" };
int[] to = new int[] { R.id.profile_name };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.profile, listViewCursor, from, to);
ListView profileList = (ListView) findViewById(R.id.profile_list);
profileList.setAdapter(adapter);
// Set the per-item click handler.
profileList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
listViewCursor.moveToPosition(position);
int brightness = listViewCursor.getInt(listViewCursor
.getColumnIndexOrThrow(DbHelper.PROF_VALUE_COL));
setBrightness(brightness);
// TODO(cgallek): This will terminate the application after a profile
// is selected. Consider making this a configurable option.
finish();
}
});
registerForContextMenu(profileList);
}
@Override
protected void onDestroy() {
dbAccessor.closeConnections();
super.onDestroy();
}
@Override
protected void onResume() {
// Lookup the initial system brightness and set our app's brightness
// percentage appropriately.
appBrightness = Util.getPhoneBrighness(getContentResolver(), dbAccessor);
// Set the value for the brightness text field and slider.
refreshDisplay();
super.onResume();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, MENU_EDIT, Menu.NONE, R.string.edit);
menu.add(Menu.NONE, MENU_DELETE, Menu.NONE, R.string.delete);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case MENU_EDIT:
listViewCursor.moveToPosition(info.position);
Intent i = new Intent(getApplication(), EditActivity.class);
i.putExtra(DbHelper.PROF_ID_COL, listViewCursor.getInt(listViewCursor
.getColumnIndexOrThrow(DbHelper.PROF_ID_COL)));
i.putExtra(DbHelper.PROF_NAME_COL, listViewCursor
.getString(listViewCursor
.getColumnIndexOrThrow(DbHelper.PROF_NAME_COL)));
i.putExtra(DbHelper.PROF_VALUE_COL, listViewCursor
.getInt(listViewCursor
.getColumnIndexOrThrow(DbHelper.PROF_VALUE_COL)));
startActivityForResult(i, ACTIVITY_EDIT);
return true;
case MENU_DELETE:
listViewCursor.moveToPosition(info.position);
int id = listViewCursor.getInt(listViewCursor
.getColumnIndexOrThrow(DbHelper.PROF_ID_COL));
dbAccessor.deletProfile(id);
listViewCursor.requery();
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
MenuItem calibrate = menu.add(0, OPTION_CALIBRATE, 0, R.string.calibrate);
calibrate.setIcon(android.R.drawable.ic_menu_preferences);
return result;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean result = super.onPrepareOptionsMenu(menu);
// Don't setup the calibrate menu item if auto brightness is enabled.
// Trying to calibrate while it's on is weird...
MenuItem calibrate = menu.findItem(OPTION_CALIBRATE);
if (Util.supportsAutoBrightness(getContentResolver()) &&
Util.getAutoBrightnessEnabled(getContentResolver())) {
calibrate.setEnabled(false);
} else {
calibrate.setEnabled(true);
}
return result;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case OPTION_CALIBRATE:
Intent i = new android.content.Intent(getApplicationContext(),
CalibrateActivity.class);
startActivityForResult(i, ACTIVITY_CALIBRATE);
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
setBrightness(getBrightness() - 10);
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
setBrightness(getBrightness() + 10);
return true;
default:
return super.onKeyDown(keyCode, event);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
return;
}
if (requestCode != ACTIVITY_EDIT) {
return;
}
Bundle extras = data.getExtras();
int id = extras.getInt(DbHelper.PROF_ID_COL);
switch (resultCode) {
case Activity.RESULT_OK:
String name = extras.getString(DbHelper.PROF_NAME_COL);
int brightness = extras.getInt(DbHelper.PROF_VALUE_COL);
dbAccessor.updateProfile(id, name, brightness);
listViewCursor.requery();
break;
}
}
private void refreshDisplay() {
TextView brightnessText = (TextView) findViewById(R.id.brightness);
brightnessText.setText(getString(R.string.brightness) + " "
+ getBrightness() + "%");
SeekBar slider = (SeekBar) findViewById(R.id.slider);
slider.setProgress(getBrightness());
// Show/Hide the auto brightness check box.
CheckBox checkbox = (CheckBox) findViewById(R.id.auto_brightness);
if (Util.supportsAutoBrightness(getContentResolver())) {
checkbox.setVisibility(View.VISIBLE);
if (Util.getAutoBrightnessEnabled(getContentResolver())) {
checkbox.setChecked(true);
lockBrightnessControls(true);
} else {
checkbox.setChecked(false);
lockBrightnessControls(false);
}
} else {
checkbox.setVisibility(View.GONE);
lockBrightnessControls(false);
}
}
private int getBrightness() {
return appBrightness;
}
private void setBrightness(int brightness) {
// Don't try to adjust brightness if auto brightness is enabled.
if (Util.supportsAutoBrightness(getContentResolver()) &&
Util.getAutoBrightnessEnabled(getContentResolver())) {
return;
}
if (brightness < 0) {
appBrightness = 0;
} else if (brightness > 100) {
appBrightness = 100;
} else {
appBrightness = brightness;
}
Util.setPhoneBrightness(getContentResolver(), getWindow(), dbAccessor,
appBrightness);
refreshDisplay();
}
private void lockBrightnessControls(boolean lock) {
SeekBar slider = (SeekBar) findViewById(R.id.slider);
ListView profileList = (ListView) findViewById(R.id.profile_list);
// Note: setEnabled() doesn't seem to work with this ListView, nor does
// calling setEnabled() on the individual children of the ListView.
// The items become grayed out, but the click handlers are still registered.
// As a work around, simply hide the entire list view.
if (lock) {
profileList.setVisibility(View.GONE);
slider.setEnabled(false);
} else {
profileList.setVisibility(View.VISIBLE);
slider.setEnabled(true);
}
}
}
| 0indri0-1111 | android/brightnessprof/src/com/angrydoughnuts/android/brightprof/BrightnessProfiles.java | Java | asf20 | 11,294 |
/****************************************************************************
* Copyright 2009 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.brightprof;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class EditActivity extends Activity {
private static final int UNKNOWN_ID = -1;
private int profile_id_ = UNKNOWN_ID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit);
Button okButton = (Button) findViewById(R.id.ok_button);
Button cancelButton = (Button) findViewById(R.id.cancel_button);
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setResult(RESULT_CANCELED);
finish();
}
});
final EditText nameBox = (EditText) findViewById(R.id.edit_name);
final EditText brightnessBox = (EditText) findViewById(R.id.edit_brightness);
final String name;
final int brightness;
Bundle extras = getIntent().getExtras();
if (extras == null) {
profile_id_ = UNKNOWN_ID;
name = "";
brightness = -1;
} else {
profile_id_ = extras.getInt(DbHelper.PROF_ID_COL);
name = extras.getString(DbHelper.PROF_NAME_COL);
brightness = extras.getInt(DbHelper.PROF_VALUE_COL);
nameBox.setText(name);
brightnessBox.setText(Integer.toString(brightness));
}
okButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String newName = nameBox.getText().toString();
String brightnessText = brightnessBox.getText().toString();
int newBrightness = brightness;
try {
newBrightness = Integer.parseInt(brightnessText);
} catch (NumberFormatException e) {
newBrightness = -1;
}
if (newName.length() == 0 || newBrightness < 0 || newBrightness > 100) {
// TODO display some kind of error message?
return;
}
// If nothing changed, act as though cancel was pressed.
if (name.equals(newName) && brightness == newBrightness) {
setResult(RESULT_CANCELED);
finish();
}
// Bundle up the new values.
Bundle bundle = new Bundle();
bundle.putInt(DbHelper.PROF_ID_COL, profile_id_);
bundle.putString(DbHelper.PROF_NAME_COL, newName);
bundle.putInt(DbHelper.PROF_VALUE_COL, newBrightness);
Intent intent = new Intent();
intent.putExtras(bundle);
setResult(RESULT_OK, intent);
finish();
}
});
}
}
| 0indri0-1111 | android/brightnessprof/src/com/angrydoughnuts/android/brightprof/EditActivity.java | Java | asf20 | 3,369 |
/****************************************************************************
* Copyright 2009 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.brightprof;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class DbAccessor {
private DbHelper db;
private SQLiteDatabase rDb;
private SQLiteDatabase rwDb;
public DbAccessor(Context context) {
db = new DbHelper(context);
rDb = db.getReadableDatabase();
rwDb = db.getWritableDatabase();
}
public void closeConnections() {
rDb.close();
rwDb.close();
}
public Cursor getAllProfiles() {
return rDb.query(DbHelper.DB_TABLE_PROFILES,
new String[] { DbHelper.PROF_ID_COL, DbHelper.PROF_NAME_COL,
DbHelper.PROF_VALUE_COL }, null, null, null, null, null);
}
public void updateProfile(int rowId, String name, int brightness) {
ContentValues values = new ContentValues(2);
values.put(DbHelper.PROF_NAME_COL, name);
values.put(DbHelper.PROF_VALUE_COL, brightness);
// If this is an unknown row id, create a new row.
if (rowId < 0) {
rwDb.insert(DbHelper.DB_TABLE_PROFILES, null, values);
// Otherwise, update the supplied row id.
} else {
String where = DbHelper.PROF_ID_COL + " = " + rowId;
rwDb.update(DbHelper.DB_TABLE_PROFILES, values, where, null);
}
}
public void deletProfile(int rowId) {
String where = DbHelper.PROF_ID_COL + " = " + rowId;
rwDb.delete(DbHelper.DB_TABLE_PROFILES, where, null);
}
public int getMinimumBrightness() {
Cursor c = rDb.query(DbHelper.DB_TABLE_CALIBRATE,
new String[] { DbHelper.CALIB_MIN_BRIGHT_COL }, null, null, null, null,
null);
c.moveToFirst();
int b = c.getInt(c.getColumnIndexOrThrow(DbHelper.CALIB_MIN_BRIGHT_COL));
c.deactivate();
c.close();
return b;
}
public void setMinimumBrightness(int brightness) {
ContentValues values = new ContentValues(1);
values.put(DbHelper.CALIB_MIN_BRIGHT_COL, brightness);
rwDb.update(DbHelper.DB_TABLE_CALIBRATE, values, null, null);
}
}
| 0indri0-1111 | android/brightnessprof/src/com/angrydoughnuts/android/brightprof/DbAccessor.java | Java | asf20 | 2,803 |
/****************************************************************************
* Copyright 2009 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.brightprof;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class CalibrateActivity extends Activity {
private int minBrightness = 20;
private DbAccessor db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calibrate);
Button okButton = (Button) findViewById(R.id.ok_button);
Button cancelButton = (Button) findViewById(R.id.cancel_button);
db = new DbAccessor(this);
okButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
db.setMinimumBrightness(minBrightness);
// If the new minimum brightness is greater than the current screen
// setting, update the setting.
if (minBrightness > Util.getSystemBrightness(getContentResolver())) {
Util.setSystemBrightness(getContentResolver(), minBrightness);
}
setResult(RESULT_OK);
finish();
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setResult(RESULT_CANCELED);
finish();
}
});
}
@Override
protected void onDestroy() {
db.closeConnections();
super.onDestroy();
}
@Override
protected void onResume() {
super.onResume();
updateDisplay();
Util.setActivityBrightness(getWindow(), minBrightness);
TextView current_minimum_brightness =
(TextView) findViewById(R.id.current_min_brightness);
current_minimum_brightness.setText("" + db.getMinimumBrightness());
}
@Override
protected void onPause() {
// Return the brightness to it's previous state when the dialog closes.
Util.setActivityBrightness(getWindow(), -1);
super.onPause();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
// Don't allow this value to go to 0. It shuts the screen off.
if (minBrightness > 1) {
minBrightness -= 1;
updateDisplay();
Util.setActivityBrightness(getWindow(), minBrightness);
}
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
if (minBrightness < 255) {
minBrightness += 1;
updateDisplay();
Util.setActivityBrightness(getWindow(), minBrightness);
}
return true;
default:
return super.onKeyDown(keyCode, event);
}
}
private void updateDisplay() {
TextView test_min_brightness =
(TextView) findViewById(R.id.test_min_brightness);
test_min_brightness.setText("" + minBrightness);
}
}
| 0indri0-1111 | android/brightnessprof/src/com/angrydoughnuts/android/brightprof/CalibrateActivity.java | Java | asf20 | 3,556 |
/****************************************************************************
* Copyright 2009 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.brightprof;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "brightprof";
public static final String DB_TABLE_PROFILES = "profiles";
public static final String DB_TABLE_CALIBRATE = "calibrate";
public static final int DB_VERSION = 3;
public static final String PROF_ID_COL = "_id";
public static final String PROF_NAME_COL = "name";
public static final String PROF_VALUE_COL = "value";
public static final String CALIB_MIN_BRIGHT_COL = "min_bright";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// Table to hold information for each profile.
db.execSQL("CREATE TABLE " + DB_TABLE_PROFILES + " (" + PROF_ID_COL
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + PROF_NAME_COL
+ " TEXT NOT NULL," + PROF_VALUE_COL + " UNSIGNED INTEGER (0, 100))");
db.execSQL("INSERT INTO " + DB_TABLE_PROFILES + "( " + PROF_NAME_COL + ", "
+ PROF_VALUE_COL + ") VALUES ('Low', 0)");
db.execSQL("INSERT INTO " + DB_TABLE_PROFILES + "( " + PROF_NAME_COL + ", "
+ PROF_VALUE_COL + ") VALUES ('Normal', 15)");
db.execSQL("INSERT INTO " + DB_TABLE_PROFILES + "( " + PROF_NAME_COL + ", "
+ PROF_VALUE_COL + ") VALUES ('High', 100)");
createCalibrationTable(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// DB version 3 added a table for keeping track of minimum brightness.
// It is no longer necessary to enforce this minimum in the profile table
// (as values 0 through 100 are now valid).
// This creates the new minimum brightness table for old installs.
if (oldVersion < 3) {
createCalibrationTable(db);
}
}
void createCalibrationTable(SQLiteDatabase db) {
// Table to hold calibration settings.
db.execSQL("CREATE TABLE " + DB_TABLE_CALIBRATE + " ("
+ CALIB_MIN_BRIGHT_COL + " UNSIGNED INTEGER (1, 255))");
db.execSQL("INSERT INTO " + DB_TABLE_CALIBRATE + "( "
+ CALIB_MIN_BRIGHT_COL + ") VALUES (10)");
}
}
| 0indri0-1111 | android/brightnessprof/src/com/angrydoughnuts/android/brightprof/DbHelper.java | Java | asf20 | 3,040 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import java.util.Calendar;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Handler;
import android.text.format.DateFormat;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewStub;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
/**
* This class is a slight improvement over the android time picker dialog.
* It allows the user to select hour, minute, and second (the android picker
* does not support seconds). It also has a configurable increment feature
* (30, 5, and 1).
*/
public final class TimePickerDialog extends AlertDialog {
public interface OnTimeSetListener {
public void onTimeSet(int hourOfDay, int minute, int second);
}
private static final String PICKER_PREFS = "TimePickerPreferences";
private static final String INCREMENT_PREF = "increment";
private OnTimeSetListener listener;
private SharedPreferences prefs;
private Calendar calendar;
private TextView timeText;
private Button amPmButton;
private PickerView hourPicker;
private PickerView minutePicker;
private PickerView secondPicker;
/**
* Construct a time picker with the supplied hour minute and second.
* @param context
* @param title Dialog title.
* @param hourOfDay 0 to 23.
* @param minute 0 to 60.
* @param second 0 to 60.
* @param showSeconds Show/hide the seconds field.
* @param setListener Callback for when the user selects 'OK'.
*/
public TimePickerDialog(Context context, String title,
int hourOfDay, int minute, int second, final boolean showSeconds,
OnTimeSetListener setListener) {
this(context, title, showSeconds, setListener);
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
hourPicker.pickerRefresh();
calendar.set(Calendar.MINUTE, minute);
minutePicker.pickerRefresh();
calendar.set(Calendar.SECOND, second);
if (showSeconds) {
secondPicker.pickerRefresh();
}
dialogRefresh();
}
/**
* Construct a time picker with 'now' as the starting time.
* @param context
* @param title Dialog title.
* @param showSeconds Show/hid the seconds field.
* @param setListener Callback for when the user selects 'OK'.
*/
public TimePickerDialog(Context context, String title, final boolean showSeconds,
OnTimeSetListener setListener) {
super(context);
listener = setListener;
prefs = context.getSharedPreferences(PICKER_PREFS, Context.MODE_PRIVATE);
calendar = Calendar.getInstance();
// The default increment amount is stored in a shared preference. Look
// it up.
final int incPref = prefs.getInt(INCREMENT_PREF, IncrementValue.FIVE.ordinal());
final IncrementValue defaultIncrement = IncrementValue.values()[incPref];
// OK button setup.
setButton(AlertDialog.BUTTON_POSITIVE, context.getString(R.string.ok),
new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
if (listener == null) {
return;
}
int seconds = showSeconds ? calendar.get(Calendar.SECOND) : 0;
listener.onTimeSet(
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
seconds);
}
});
// Cancel button setup.
setButton(AlertDialog.BUTTON_NEGATIVE, context.getString(R.string.cancel),
new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
cancel();
}
});
// Set title and icon.
if (title.length() != 0) {
setTitle(title);
setIcon(R.drawable.ic_dialog_time);
}
// Set the view for the body section of the AlertDialog.
final LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View body_view = inflater.inflate(R.layout.time_picker_dialog, null);
setView(body_view);
// Setup each of the components of the body section.
timeText = (TextView) body_view.findViewById(R.id.picker_text);
amPmButton = (Button) body_view.findViewById(R.id.picker_am_pm);
amPmButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (calendar.get(Calendar.AM_PM) == Calendar.AM) {
calendar.set(Calendar.AM_PM, Calendar.PM);
} else {
calendar.set(Calendar.AM_PM, Calendar.AM);
}
dialogRefresh();
}
});
// Setup the three time fields.
if (DateFormat.is24HourFormat(getContext())) {
body_view.findViewById(R.id.picker_am_pm_layout).setVisibility(View.GONE);
hourPicker = new PickerView(Calendar.HOUR_OF_DAY, "%02d");
} else {
body_view.findViewById(R.id.picker_am_pm_layout).setVisibility(View.VISIBLE);
hourPicker = new PickerView(Calendar.HOUR, "%d");
}
hourPicker.inflate(body_view, R.id.picker_hour, false, IncrementValue.ONE);
minutePicker = new PickerView(Calendar.MINUTE, "%02d");
minutePicker.inflate(body_view, R.id.picker_minute, true, defaultIncrement);
if (showSeconds) {
secondPicker = new PickerView(Calendar.SECOND, "%02d");
secondPicker.inflate(body_view, R.id.picker_second, true, defaultIncrement);
}
dialogRefresh();
}
private void dialogRefresh() {
AlarmTime time = new AlarmTime(
calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE),
calendar.get(Calendar.SECOND));
timeText.setText(time.timeUntilString(getContext()));
if (calendar.get(Calendar.AM_PM) == Calendar.AM) {
amPmButton.setText(getContext().getString(R.string.am));
} else {
amPmButton.setText(getContext().getString(R.string.pm));
}
}
/**
* Enum that represents the states of the increment picker button.
*/
private enum IncrementValue {
FIVE(5), ONE(1);
private int value;
IncrementValue(int value) {
this.value = value;
}
public int value() {
return value;
}
}
/**
* Helper class that wraps up the view elements of each number picker
* (plus/minus button, text field, increment picker).
*/
private final class PickerView {
private int calendarField;
private String formatString;
private EditText text = null;
private Increment increment = null;
private Button incrementValueButton = null;
private Button plus = null;
private Button minus = null;
/**
* Construct a numeric picker for the supplied calendar field and formats
* it according to the supplied format string.
* @param calendarField
* @param formatString
*/
public PickerView(int calendarField, String formatString) {
this.calendarField = calendarField;
this.formatString = formatString;
}
/**
* Inflates the ViewStub for this numeric picker.
* @param parentView
* @param resourceId
* @param showIncrement
* @param defaultIncrement
*/
public void inflate(View parentView, int resourceId, boolean showIncrement, IncrementValue defaultIncrement) {
final ViewStub stub = (ViewStub) parentView.findViewById(resourceId);
final View view = stub.inflate();
text = (EditText) view.findViewById(R.id.time_value);
text.setOnFocusChangeListener(new TextChangeListener());
text.setOnEditorActionListener(new TextChangeListener());
increment = new Increment(defaultIncrement);
incrementValueButton = (Button) view.findViewById(R.id.time_increment);
incrementValueButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
increment.cycleToNext();
Editor editor = prefs.edit();
editor.putInt(INCREMENT_PREF, increment.value.ordinal());
editor.commit();
pickerRefresh();
}
});
if (showIncrement) {
incrementValueButton.setVisibility(View.VISIBLE);
} else {
incrementValueButton.setVisibility(View.GONE);
}
plus = (Button) view.findViewById(R.id.time_plus);
TimeIncrementListener incrementListener = new TimeIncrementListener();
plus.setOnClickListener(incrementListener);
plus.setOnTouchListener(incrementListener);
plus.setOnLongClickListener(incrementListener);
minus = (Button) view.findViewById(R.id.time_minus);
TimeDecrementListener decrementListener= new TimeDecrementListener();
minus.setOnClickListener(decrementListener);
minus.setOnTouchListener(decrementListener);
minus.setOnLongClickListener(decrementListener);
pickerRefresh();
}
public void pickerRefresh() {
int fieldValue = calendar.get(calendarField);
if (calendarField == Calendar.HOUR && fieldValue == 0) {
fieldValue = 12;
}
text.setText(String.format(formatString, fieldValue));
incrementValueButton.setText("+/- " + increment.nextValue().value());
plus.setText("+" + increment.value());
minus.setText("-" + increment.value());
dialogRefresh();
}
private final class Increment {
private IncrementValue value;
public Increment(IncrementValue value) {
this.value = value;
}
public IncrementValue nextValue() {
int nextIndex = (value.ordinal() + 1) % IncrementValue.values().length;
return IncrementValue.values()[nextIndex];
}
public void cycleToNext() {
value = nextValue();
}
public int value() {
return value.value();
}
}
/**
* Listener that figures out what the next value should be when a numeric
* picker plus/minus button is clicked. It will round up/down to the next
* interval increment then increment by the increment amount on subsequent
* clicks.
*/
private abstract class TimeAdjustListener implements
View.OnClickListener, View.OnTouchListener, View.OnLongClickListener {
protected abstract int sign();
private void adjust() {
int currentValue = calendar.get(calendarField);
int remainder = currentValue % increment.value();
if (remainder == 0) {
calendar.roll(calendarField, sign() * increment.value());
} else {
int difference;
if (sign() > 0) {
difference = increment.value() - remainder;
} else {
difference = -1 * remainder;
}
calendar.roll(calendarField, difference);
}
pickerRefresh();
}
private Handler handler = new Handler();
private Runnable delayedAdjust = new Runnable() {
@Override
public void run() {
adjust();
handler.postDelayed(delayedAdjust, 150);
}
};
@Override
public void onClick(View v) {
adjust();
}
@Override
public boolean onLongClick(View v) {
delayedAdjust.run();
return false;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
handler.removeCallbacks(delayedAdjust);
}
return false;
}
}
private final class TimeIncrementListener extends TimeAdjustListener {
@Override
protected int sign() {
return 1;
}
}
private final class TimeDecrementListener extends TimeAdjustListener {
@Override
protected int sign() { return -1; }
}
/**
* Listener to handle direct user input into the time picker text fields.
* Updates after the editor confirmation button is picked or when the
* text field loses focus.
*/
private final class TextChangeListener implements OnFocusChangeListener, OnEditorActionListener {
private void handleChange() {
try {
int newValue = Integer.parseInt(text.getText().toString());
if (calendarField == Calendar.HOUR &&
newValue == 12 &&
calendar.get(Calendar.AM_PM) == Calendar.AM) {
calendar.set(Calendar.HOUR_OF_DAY, 0);
} else if (calendarField == Calendar.HOUR &&
newValue == 12 &&
calendar.get(Calendar.AM_PM) == Calendar.PM) {
calendar.set(Calendar.HOUR_OF_DAY, 12);
} else {
calendar.set(calendarField, newValue);
}
} catch (NumberFormatException e) {}
pickerRefresh();
}
@Override
public void onFocusChange(View v, boolean hasFocus) {
handleChange();
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
handleChange();
return false;
}
}
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/TimePickerDialog.java | Java | asf20 | 13,906 |
package com.angrydoughnuts.android.alarmclock;
interface NotificationServiceInterface {
long currentAlarmId();
int firingAlarmCount();
float volume();
void acknowledgeCurrentNotification(int snoozeMinutes);
} | 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/NotificationServiceInterface.aidl | AIDL | asf20 | 217 |
package com.angrydoughnuts.android.alarmclock;
parcelable AlarmTime; | 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/AlarmTime.aidl | AIDL | asf20 | 69 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.provider.MediaStore.Audio.Albums;
import android.provider.MediaStore.Audio.ArtistColumns;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ViewFlipper;
public class MediaArtistsView extends MediaListView {
private final String[] artistsColumns = new String[] {
ArtistColumns.ARTIST,
ArtistColumns.ARTIST_KEY
};
private final int[] artistsResIDs = new int[] {
R.id.media_value,
R.id.media_key
};
private MediaAlbumsView albumsView;
public MediaArtistsView(Context context) {
this(context, null);
}
public MediaArtistsView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MediaArtistsView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
albumsView = new MediaAlbumsView(context);
}
@Override
public void setCursorManager(Activity activity) {
super.setCursorManager(activity);
albumsView.setCursorManager(activity);
}
@Override
public void addToFlipper(ViewFlipper flipper) {
super.addToFlipper(flipper);
albumsView.addToFlipper(flipper);
}
public void setMediaPlayer(MediaPlayer mPlayer) {
albumsView.setMediaPlayer(mPlayer);
}
public void query(Uri contentUri) {
query(contentUri, null);
}
public void query(Uri contentUri, String selection) {
super.query(contentUri, ArtistColumns.ARTIST_KEY, selection, R.layout.media_picker_row, artistsColumns, artistsResIDs);
}
@Override
public void setMediaPickListener(OnItemPickListener listener) {
albumsView.setMediaPickListener(listener);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
super.onItemClick(parent, view, position, id);
albumsView.query(Albums.EXTERNAL_CONTENT_URI, ArtistColumns.ARTIST_KEY + " = '" + getLastSelectedName() + "'");
getFlipper().setInAnimation(getContext(), R.anim.slide_in_left);
getFlipper().setOutAnimation(getContext(), R.anim.slide_out_left);
getFlipper().showNext();
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/MediaArtistsView.java | Java | asf20 | 3,018 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
/**
* This is the main Activity for the application. It contains a ListView
* for displaying all alarms, a simple clock, and a button for adding new
* alarms. The context menu allows the user to edit default settings. Long-
* clicking on the clock will trigger a dialog for enabling/disabling 'debug
* mode.'
*/
public final class ActivityAlarmClock extends Activity {
private enum Dialogs { TIME_PICKER, DELETE_CONFIRM };
private enum Menus { DELETE_ALL, DEFAULT_ALARM_SETTINGS, APP_SETTINGS };
private AlarmClockServiceBinder service;
private NotificationServiceBinder notifyService;
private DbAccessor db;
private AlarmViewAdapter adapter;
private TextView clock;
private Button testBtn;
private Button pendingBtn;
private Handler handler;
private Runnable tickCallback;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alarm_list);
// Access to in-memory and persistent data structures.
service = new AlarmClockServiceBinder(getApplicationContext());
db = new DbAccessor(getApplicationContext());
handler = new Handler();
notifyService = new NotificationServiceBinder(getApplicationContext());
// Setup individual UI elements.
// A simple clock.
clock = (TextView) findViewById(R.id.clock);
// Used in debug mode. Schedules an alarm for 5 seconds in the future
// when clicked.
testBtn = (Button) findViewById(R.id.test_alarm);
testBtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
final Calendar testTime = Calendar.getInstance();
testTime.add(Calendar.SECOND, 5);
service.createAlarm(new AlarmTime(testTime.get(
Calendar.HOUR_OF_DAY),
testTime.get(Calendar.MINUTE),
testTime.get(Calendar.SECOND)));
adapter.requery();
}
});
// Displays a list of pending alarms (only visible in debug mode).
pendingBtn = (Button) findViewById(R.id.pending_alarms);
pendingBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(
new Intent(getApplicationContext(), ActivityPendingAlarms.class));
}
});
// Opens the time picker dialog and allows the user to schedule a new alarm.
Button addBtn = (Button) findViewById(R.id.add_alarm);
addBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
showDialog(Dialogs.TIME_PICKER.ordinal());
}
});
// Setup the alarm list and the underlying adapter. Clicking an individual
// item will start the settings activity.
final ListView alarmList = (ListView) findViewById(R.id.alarm_list);
adapter = new AlarmViewAdapter(this, db, service);
alarmList.setAdapter(adapter);
alarmList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
final AlarmInfo info = (AlarmInfo) adapter.getItemAtPosition(position);
final Intent i = new Intent(getApplicationContext(), ActivityAlarmSettings.class);
i.putExtra(ActivityAlarmSettings.EXTRAS_ALARM_ID, info.getAlarmId());
startActivity(i);
}
});
// This is a self-scheduling callback that is responsible for refreshing
// the screen. It is started in onResume() and stopped in onPause().
tickCallback = new Runnable() {
@Override
public void run() {
// Redraw the screen.
redraw();
// Schedule the next update on the next interval boundary.
AlarmUtil.Interval interval = AlarmUtil.Interval.MINUTE;
if (AppSettings.isDebugMode(getApplicationContext())) {
interval = AlarmUtil.Interval.SECOND;
}
long next = AlarmUtil.millisTillNextInterval(interval);
handler.postDelayed(tickCallback, next);
}
};
}
@Override
protected void onResume() {
super.onResume();
service.bind();
handler.post(tickCallback);
adapter.requery();
notifyService.bind();
notifyService.call(new NotificationServiceBinder.ServiceCallback() {
@Override
public void run(NotificationServiceInterface service) {
int count;
try {
count = service.firingAlarmCount();
} catch (RemoteException e) {
return;
} finally {
handler.post(new Runnable() {
@Override
public void run() {
notifyService.unbind();
}
});
}
if (count > 0) {
Intent notifyActivity = new Intent(getApplicationContext(), ActivityAlarmNotification.class);
notifyActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(notifyActivity);
}
}
});
}
@Override
protected void onPause() {
super.onPause();
handler.removeCallbacks(tickCallback);
service.unbind();
}
@Override
protected void onDestroy() {
super.onDestroy();
db.closeConnections();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem delete_all =
menu.add(0, Menus.DELETE_ALL.ordinal(), 0, R.string.delete_all);
delete_all.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
MenuItem alarm_settings =
menu.add(0, Menus.DEFAULT_ALARM_SETTINGS.ordinal(), 0, R.string.default_settings);
alarm_settings.setIcon(android.R.drawable.ic_lock_idle_alarm);
MenuItem app_settings =
menu.add(0, Menus.APP_SETTINGS.ordinal(), 0, R.string.app_settings);
app_settings.setIcon(android.R.drawable.ic_menu_preferences);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (Menus.values()[item.getItemId()]) {
case DELETE_ALL:
showDialog(Dialogs.DELETE_CONFIRM.ordinal());
break;
case DEFAULT_ALARM_SETTINGS:
Intent alarm_settings = new Intent(getApplicationContext(), ActivityAlarmSettings.class);
alarm_settings.putExtra(
ActivityAlarmSettings.EXTRAS_ALARM_ID, AlarmSettings.DEFAULT_SETTINGS_ID);
startActivity(alarm_settings);
break;
case APP_SETTINGS:
Intent app_settings = new Intent(getApplicationContext(), ActivityAppSettings.class);
startActivity(app_settings);
break;
}
return super.onOptionsItemSelected(item);
}
private final void redraw() {
// Show/hide debug buttons.
if (AppSettings.isDebugMode(getApplicationContext())) {
testBtn.setVisibility(View.VISIBLE);
pendingBtn.setVisibility(View.VISIBLE);
} else {
testBtn.setVisibility(View.GONE);
pendingBtn.setVisibility(View.GONE);
}
// Recompute expiration times in the list view
adapter.notifyDataSetChanged();
// Update clock
Calendar c = Calendar.getInstance();
AlarmTime time = new AlarmTime(
c.get(Calendar.HOUR_OF_DAY),
c.get(Calendar.MINUTE),
c.get(Calendar.SECOND));
clock.setText(time.localizedString(getApplicationContext()));
}
@Override
protected Dialog onCreateDialog(int id) {
switch (Dialogs.values()[id]) {
case TIME_PICKER:
Dialog picker = new TimePickerDialog(
this, getString(R.string.add_alarm), AppSettings.isDebugMode(this),
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(int hourOfDay, int minute, int second) {
// When a time is selected, create it via the service and
// force the list view to re-query the alarm list.
service.createAlarm(new AlarmTime(hourOfDay, minute, second));
adapter.requery();
// Destroy this dialog so that it does not save its state.
removeDialog(Dialogs.TIME_PICKER.ordinal());
}
});
picker.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
removeDialog(Dialogs.TIME_PICKER.ordinal());
}
});
return picker;
case DELETE_CONFIRM:
final AlertDialog.Builder deleteConfirmBuilder = new AlertDialog.Builder(this);
deleteConfirmBuilder.setTitle(R.string.delete_all);
deleteConfirmBuilder.setMessage(R.string.confirm_delete);
deleteConfirmBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
service.deleteAllAlarms();
adapter.requery();
dismissDialog(Dialogs.DELETE_CONFIRM.ordinal());
}
});
deleteConfirmBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismissDialog(Dialogs.DELETE_CONFIRM.ordinal());
}
});
return deleteConfirmBuilder.create();
default:
return super.onCreateDialog(id);
}
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/ActivityAlarmClock.java | Java | asf20 | 10,669 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.provider.MediaStore.Audio.AlbumColumns;
import android.provider.MediaStore.Audio.Media;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ViewFlipper;
public class MediaAlbumsView extends MediaListView {
private final String[] albumsColumns = new String[] {
AlbumColumns.ALBUM,
AlbumColumns.ALBUM_KEY
};
private final int[] albumsResIDs = new int[] {
R.id.media_value,
R.id.media_key
};
private MediaSongsView songsView;
public MediaAlbumsView(Context context) {
this(context, null);
}
public MediaAlbumsView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MediaAlbumsView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
overrideSortOrder(AlbumColumns.ALBUM + " ASC");
songsView = new MediaSongsView(context);
songsView.overrideSortOrder(null);
}
@Override
public void setCursorManager(Activity activity) {
super.setCursorManager(activity);
songsView.setCursorManager(activity);
}
@Override
public void addToFlipper(ViewFlipper flipper) {
super.addToFlipper(flipper);
songsView.addToFlipper(flipper);
}
public void setMediaPlayer(MediaPlayer mPlayer) {
songsView.setMediaPlayer(mPlayer);
}
public void query(Uri contentUri) {
query(contentUri, null);
}
public void query(Uri contentUri, String selection) {
super.query(contentUri, AlbumColumns.ALBUM_KEY, selection, R.layout.media_picker_row, albumsColumns, albumsResIDs);
}
@Override
public void setMediaPickListener(OnItemPickListener listener) {
songsView.setMediaPickListener(listener);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
super.onItemClick(parent, view, position, id);
songsView.query(Media.EXTERNAL_CONTENT_URI, AlbumColumns.ALBUM_KEY + " = '" + getLastSelectedName() + "'");
getFlipper().setInAnimation(getContext(), R.anim.slide_in_left);
getFlipper().setOutAnimation(getContext(), R.anim.slide_out_left);
getFlipper().showNext();
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/MediaAlbumsView.java | Java | asf20 | 3,081 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import java.util.LinkedList;
import com.angrydoughnuts.android.alarmclock.WakeLock.WakeLockException;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Vibrator;
/**
* This service is responsible for notifying the user when an alarm is
* triggered. The pending intent delivered by the alarm manager service
* will trigger the alarm receiver. This receiver will in turn start
* this service, passing the appropriate alarm url as data in the intent.
* This service is capable of receiving multiple alarm notifications
* without acknowledgments and will queue them until they are sequentially
* acknowledged. The service is capable of playing a sound, triggering
* the vibrator and displaying the notification activity (used to acknowledge
* alarms).
*/
public class NotificationService extends Service {
public class NoAlarmsException extends Exception {
private static final long serialVersionUID = 1L;
}
// Since the media player objects are expensive to create and destroy,
// share them across invocations of this service (there should never be
// more than one instance of this class in a given application).
private enum MediaSingleton {
INSTANCE;
private MediaPlayer mediaPlayer = null;
private Ringtone fallbackSound = null;
private Vibrator vibrator = null;
MediaSingleton() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
}
// Force the alarm stream to be maximum volume. This will allow the user
// to select a volume between 0 and 100 percent via the settings activity.
private void normalizeVolume(Context c, float startVolume) {
final AudioManager audio =
(AudioManager) c.getSystemService(Context.AUDIO_SERVICE);
audio.setStreamVolume(AudioManager.STREAM_ALARM,
audio.getStreamMaxVolume(AudioManager.STREAM_ALARM), 0);
setVolume(startVolume);
}
private void setVolume(float volume) {
mediaPlayer.setVolume(volume, volume);
}
private void useContext(Context c) {
// The media player can fail for lots of reasons. Try to setup a backup
// sound for use when the media player fails.
fallbackSound = RingtoneManager.getRingtone(c, AlarmUtil.getDefaultAlarmUri());
if (fallbackSound == null) {
Uri superFallback = RingtoneManager.getValidRingtoneUri(c);
fallbackSound = RingtoneManager.getRingtone(c, superFallback);
}
// Make the fallback sound use the alarm stream as well.
if (fallbackSound != null) {
fallbackSound.setStreamType(AudioManager.STREAM_ALARM);
}
// Instantiate a vibrator. That's fun to say.
vibrator = (Vibrator) c.getSystemService(Context.VIBRATOR_SERVICE);
}
private void ensureSound() {
if (!mediaPlayer.isPlaying() &&
fallbackSound != null && !fallbackSound.isPlaying()) {
fallbackSound.play();
}
}
private void vibrate() {
if (vibrator != null) {
vibrator.vibrate(new long[] {500, 500}, 0);
}
}
public void play(Context c, Uri tone) {
mediaPlayer.reset();
mediaPlayer.setLooping(true);
try {
mediaPlayer.setDataSource(c, tone);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stop() {
mediaPlayer.stop();
if (vibrator != null) {
vibrator.cancel();
}
if (fallbackSound != null) {
fallbackSound.stop();
}
}
}
// Data
private LinkedList<Long> firingAlarms;
private AlarmClockServiceBinder service;
private DbAccessor db;
// Notification tools
private NotificationManager manager;
private Notification notification;
private PendingIntent notificationActivity;
private Handler handler;
private VolumeIncreaser volumeIncreaseCallback;
private Runnable soundCheck;
private Runnable notificationBlinker;
private Runnable autoCancel;
@Override
public IBinder onBind(Intent intent) {
return new NotificationServiceInterfaceStub(this);
}
@Override
public void onCreate() {
super.onCreate();
firingAlarms = new LinkedList<Long>();
// Access to in-memory and persistent data structures.
service = new AlarmClockServiceBinder(getApplicationContext());
service.bind();
db = new DbAccessor(getApplicationContext());
// Setup audio.
MediaSingleton.INSTANCE.useContext(getApplicationContext());
// Setup notification bar.
manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Use the notification activity explicitly in this intent just in case the
// activity can't be viewed via the root activity.
Intent intent = new Intent(getApplicationContext(), ActivityAlarmNotification.class);
notificationActivity = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
notification = new Notification(R.drawable.alarmclock_notification, null, 0);
notification.flags |= Notification.FLAG_ONGOING_EVENT;
// Setup a self-scheduling event loops.
handler = new Handler();
volumeIncreaseCallback = new VolumeIncreaser();
soundCheck = new Runnable() {
@Override
public void run() {
// Some sound should always be playing.
MediaSingleton.INSTANCE.ensureSound();
long next = AlarmUtil.millisTillNextInterval(AlarmUtil.Interval.SECOND);
handler.postDelayed(soundCheck, next);
}
};
notificationBlinker = new Runnable() {
@Override
public void run() {
String notifyText;
try {
AlarmInfo info = db.readAlarmInfo(currentAlarmId());
notifyText = info.getName();
if (notifyText.equals("")) {
notifyText = info.getTime().localizedString(getApplicationContext());
}
} catch (NoAlarmsException e) {
return;
}
notification.setLatestEventInfo(getApplicationContext(), notifyText, "", notificationActivity);
if (notification.icon == R.drawable.alarmclock_notification) {
notification.icon = R.drawable.alarmclock_notification2;
} else {
notification.icon = R.drawable.alarmclock_notification;
}
manager.notify(AlarmClockService.NOTIFICATION_BAR_ID, notification);
long next = AlarmUtil.millisTillNextInterval(AlarmUtil.Interval.SECOND);
handler.postDelayed(notificationBlinker, next);
}
};
autoCancel = new Runnable() {
@Override
public void run() {
try {
acknowledgeCurrentNotification(0);
} catch (NoAlarmsException e) {
return;
}
Intent notifyActivity = new Intent(getApplicationContext(), ActivityAlarmNotification.class);
notifyActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
notifyActivity.putExtra(ActivityAlarmNotification.TIMEOUT_COMMAND, true);
startActivity(notifyActivity);
}
};
}
@Override
public void onDestroy() {
super.onDestroy();
db.closeConnections();
service.unbind();
boolean debug = AppSettings.isDebugMode(getApplicationContext());
if (debug && firingAlarms.size() != 0) {
throw new IllegalStateException("Notification service terminated with pending notifications.");
}
try {
WakeLock.assertNoneHeld();
} catch (WakeLockException e) {
if (debug) { throw new IllegalStateException(e.getMessage()); }
}
}
// OnStart was depreciated in SDK 5. It is here for backwards compatibility.
// http://android-developers.blogspot.com/2010/02/service-api-changes-starting-with.html
@Override
public void onStart(Intent intent, int startId) {
handleStart(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleStart(intent, startId);
return START_NOT_STICKY;
}
private void handleStart(Intent intent, int startId) {
// startService called from alarm receiver with an alarm id url.
if (intent != null && intent.getData() != null) {
long alarmId = AlarmUtil.alarmUriToId(intent.getData());
try {
WakeLock.assertHeld(alarmId);
} catch (WakeLockException e) {
if (AppSettings.isDebugMode(getApplicationContext())) {
throw new IllegalStateException(e.getMessage());
}
}
Intent notifyActivity = new Intent(getApplicationContext(), ActivityAlarmNotification.class);
notifyActivity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(notifyActivity);
boolean firstAlarm = firingAlarms.size() == 0;
if (!firingAlarms.contains(alarmId)) {
firingAlarms.add(alarmId);
}
if (firstAlarm) {
soundAlarm(alarmId);
}
}
}
public long currentAlarmId() throws NoAlarmsException {
if (firingAlarms.size() == 0) {
throw new NoAlarmsException();
}
return firingAlarms.getFirst();
}
public int firingAlarmCount() {
return firingAlarms.size();
}
public float volume() {
return volumeIncreaseCallback.volume();
}
public void acknowledgeCurrentNotification(int snoozeMinutes) throws NoAlarmsException {
long alarmId = currentAlarmId();
if (firingAlarms.contains(alarmId)) {
firingAlarms.remove(alarmId);
if (snoozeMinutes <= 0) {
service.acknowledgeAlarm(alarmId);
} else {
service.snoozeAlarmFor(alarmId, snoozeMinutes);
}
}
stopNotifying();
// If this was the only alarm firing, stop the service. Otherwise,
// start the next alarm in the stack.
if (firingAlarms.size() == 0) {
stopSelf();
} else {
soundAlarm(alarmId);
}
try {
WakeLock.release(alarmId);
} catch (WakeLockException e) {
if (AppSettings.isDebugMode(getApplicationContext())) {
throw new IllegalStateException(e.getMessage());
}
}
}
private void soundAlarm(long alarmId) {
// Begin notifying based on settings for this alaram.
AlarmSettings settings = db.readAlarmSettings(alarmId);
if (settings.getVibrate()) {
MediaSingleton.INSTANCE.vibrate();
}
volumeIncreaseCallback.reset(settings);
MediaSingleton.INSTANCE.play(getApplicationContext(), settings.getTone());
// Start periodic events for handling this notification.
handler.post(volumeIncreaseCallback);
handler.post(soundCheck);
handler.post(notificationBlinker);
// Set up a canceler if this notification isn't acknowledged by the timeout.
int timeoutMillis = 60 * 1000 * AppSettings.alarmTimeOutMins(getApplicationContext());
handler.postDelayed(autoCancel, timeoutMillis);
}
private void stopNotifying() {
// Stop periodic events.
handler.removeCallbacks(volumeIncreaseCallback);
handler.removeCallbacks(soundCheck);
handler.removeCallbacks(notificationBlinker);
handler.removeCallbacks(autoCancel);
// Stop notifying.
MediaSingleton.INSTANCE.stop();
}
/**
* Helper class for gradually increasing the volume of the alarm audio
* stream.
*/
private final class VolumeIncreaser implements Runnable {
float start;
float end;
float increment;
public float volume() {
return start;
}
public void reset(AlarmSettings settings) {
start = (float) (settings.getVolumeStartPercent() / 100.0);
end = (float) (settings.getVolumeEndPercent() / 100.0);
increment = (end - start) / (float) settings.getVolumeChangeTimeSec();
MediaSingleton.INSTANCE.normalizeVolume(getApplicationContext(), start);
}
@Override
public void run() {
start += increment;
if (start > end) {
start = end;
}
MediaSingleton.INSTANCE.setVolume(start);
if (Math.abs(start - end) > (float) 0.0001) {
handler.postDelayed(volumeIncreaseCallback, 1000);
}
}
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/NotificationService.java | Java | asf20 | 13,155 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.provider.Settings;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
/**
* Simple preferences activity to display/manage the shared preferences
* that make up the global application settings.
*/
public class ActivityAppSettings extends PreferenceActivity {
private enum Dialogs { CUSTOM_LOCK_SCREEN }
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.app_settings);
OnPreferenceChangeListener refreshListener = new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
// Clear the lock screen text if the user disables the feature.
if (preference.getKey().equals(AppSettings.LOCK_SCREEN)) {
Settings.System.putString(getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED, "");
final String custom_lock_screen = getResources().getStringArray(R.array.lock_screen_values)[4];
if (newValue.equals(custom_lock_screen)) {
showDialog(Dialogs.CUSTOM_LOCK_SCREEN.ordinal());
}
}
final Intent causeRefresh = new Intent(getApplicationContext(), AlarmClockService.class);
causeRefresh.putExtra(AlarmClockService.COMMAND_EXTRA, AlarmClockService.COMMAND_NOTIFICATION_REFRESH);
startService(causeRefresh);
return true;
}
};
// Refresh the notification icon when the user changes these preferences.
final Preference notification_icon = findPreference(AppSettings.NOTIFICATION_ICON);
notification_icon.setOnPreferenceChangeListener(refreshListener);
final Preference lock_screen = findPreference(AppSettings.LOCK_SCREEN);
lock_screen.setOnPreferenceChangeListener(refreshListener);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (Dialogs.values()[id]) {
case CUSTOM_LOCK_SCREEN:
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
final View lockTextView = getLayoutInflater().inflate(R.layout.custom_lock_screen_dialog, null);
final EditText editText = (EditText) lockTextView.findViewById(R.id.custom_lock_screen_text);
editText.setText(prefs.getString(AppSettings.CUSTOM_LOCK_SCREEN_TEXT, ""));
final CheckBox persistentCheck = (CheckBox) lockTextView.findViewById(R.id.custom_lock_screen_persistent);
persistentCheck.setChecked(prefs.getBoolean(AppSettings.CUSTOM_LOCK_SCREEN_PERSISTENT, false));
final AlertDialog.Builder lockTextBuilder = new AlertDialog.Builder(this);
lockTextBuilder.setTitle(R.string.custom_lock_screen_text);
lockTextBuilder.setView(lockTextView);
lockTextBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Editor editor = prefs.edit();
editor.putString(AppSettings.CUSTOM_LOCK_SCREEN_TEXT, editText.getText().toString());
editor.putBoolean(AppSettings.CUSTOM_LOCK_SCREEN_PERSISTENT, persistentCheck.isChecked());
editor.commit();
final Intent causeRefresh = new Intent(getApplicationContext(), AlarmClockService.class);
causeRefresh.putExtra(AlarmClockService.COMMAND_EXTRA, AlarmClockService.COMMAND_NOTIFICATION_REFRESH);
startService(causeRefresh);
dismissDialog(Dialogs.CUSTOM_LOCK_SCREEN.ordinal());
}
});
lockTextBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismissDialog(Dialogs.CUSTOM_LOCK_SCREEN.ordinal());
}
});
return lockTextBuilder.create();
default:
return super.onCreateDialog(id);
}
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/ActivityAppSettings.java | Java | asf20 | 5,226 |
package com.angrydoughnuts.android.alarmclock;
import com.angrydoughnuts.android.alarmclock.AlarmTime;
interface AlarmClockInterface {
void createAlarm(in AlarmTime time);
void deleteAlarm(long alarmId);
void deleteAllAlarms();
void scheduleAlarm(long alarmId);
void unscheduleAlarm(long alarmId);
void acknowledgeAlarm(long alarmId);
void snoozeAlarm(long alarmId);
void snoozeAlarmFor(long alarmId, int minutes);
AlarmTime pendingAlarm(long alarmId);
AlarmTime[] pendingAlarmTimes();
} | 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/AlarmClockInterface.aidl | AIDL | asf20 | 509 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* This is a simple activity which displays all of the scheduled (in memory)
* alarms that currently exist (For debugging only).
*/
public final class ActivityPendingAlarms extends Activity {
boolean connected;
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pending_alarms);
connected = false;
listView = (ListView) findViewById(R.id.pending_alarm_list);
}
@Override
protected void onResume() {
super.onResume();
final Intent i = new Intent(getApplicationContext(), AlarmClockService.class);
if (!bindService(i, connection, Service.BIND_AUTO_CREATE)) {
throw new IllegalStateException("Unable to bind to AlarmClockService.");
}
}
@Override
protected void onPause() {
super.onPause();
if (connected) {
unbindService(connection);
}
}
private final ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
connected = true;
AlarmClockInterface clock = AlarmClockInterface.Stub.asInterface(service);
try {
ArrayAdapter<AlarmTime> adapter = new ArrayAdapter<AlarmTime>(
getApplicationContext(), R.layout.pending_alarms_item, clock.pendingAlarmTimes());
listView.setAdapter(adapter);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
connected = false;
}
};
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/ActivityPendingAlarms.java | Java | asf20 | 2,729 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import com.angrydoughnuts.android.alarmclock.NotificationService.NoAlarmsException;
import android.content.Context;
import android.os.RemoteException;
import android.widget.Toast;
public class NotificationServiceInterfaceStub extends NotificationServiceInterface.Stub {
private NotificationService service;
public NotificationServiceInterfaceStub(NotificationService service) {
this.service = service;
}
@Override
public long currentAlarmId() throws RemoteException {
try {
return service.currentAlarmId();
} catch (NoAlarmsException e) {
throw new RemoteException();
}
}
public int firingAlarmCount() throws RemoteException {
return service.firingAlarmCount();
}
@Override
public float volume() throws RemoteException {
return service.volume();
}
@Override
public void acknowledgeCurrentNotification(int snoozeMinutes) throws RemoteException {
debugToast("STOP NOTIFICATION");
try {
service.acknowledgeCurrentNotification(snoozeMinutes);
} catch (NoAlarmsException e) {
throw new RemoteException();
}
}
private void debugToast(String message) {
Context context = service.getApplicationContext();
if (AppSettings.isDebugMode(context)) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/NotificationServiceInterfaceStub.java | Java | asf20 | 2,129 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import java.util.ArrayList;
import java.util.Arrays;
import android.content.Context;
import android.database.MatrixCursor;
import android.database.MatrixCursor.RowBuilder;
import android.media.MediaPlayer;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.MediaStore.MediaColumns;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView;
public class MediaSongsView extends MediaListView implements OnItemClickListener {
private final String[] songsColumns = new String[] {
MediaColumns.TITLE,
};
final int[] songsResIDs = new int[] {
R.id.media_value,
};
public MediaSongsView(Context context) {
this(context, null);
}
public MediaSongsView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MediaSongsView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
overrideSortOrder(MediaColumns.TITLE + " ASC");
}
public void query(Uri contentUri) {
query(contentUri, null);
}
public void query(Uri contentUri, String selection) {
super.query(contentUri, MediaColumns.TITLE, selection, R.layout.media_picker_row, songsColumns, songsResIDs);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
super.onItemClick(parent, view, position, id);
MediaPlayer mPlayer = getMediaPlayer();
if (mPlayer == null) {
return;
}
mPlayer.reset();
try {
mPlayer.setDataSource(getContext(), getLastSelectedUri());
mPlayer.prepare();
mPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public void includeDefault() {
final ArrayList<String> defaultColumns =
new ArrayList<String>(songsColumns.length + 1);
defaultColumns.addAll(Arrays.asList(songsColumns));
defaultColumns.add(BaseColumns._ID);
final MatrixCursor defaultsCursor = new MatrixCursor(defaultColumns.toArray(new String[] {}));
RowBuilder row = defaultsCursor.newRow();
row.add("Default");
row.add(DEFAULT_TONE_INDEX);
includeStaticCursor(defaultsCursor);
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/MediaSongsView.java | Java | asf20 | 3,024 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ImageView.ScaleType;
/**
* Widget that contains a slider bar used for acknowledgments. The user
* must slide an arrow sufficiently far enough across the bar in order
* to trigger the acknowledgment.
*/
public class Slider extends ViewGroup {
public interface OnCompleteListener {
void complete();
}
private static final int FADE_MILLIS = 200;
private static final int SLIDE_MILLIS = 200;
private static final float SLIDE_ACCEL = (float) 1.0;
private static final double PERCENT_REQUIRED = 0.72;
private ImageView dot;
private TextView tray;
private boolean tracking;
private OnCompleteListener completeListener;
public Slider(Context context) {
this(context, null, 0);
}
public Slider(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public Slider(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Setup the background which 'holds' the slider.
tray = new TextView(getContext());
tray.setBackgroundResource(R.drawable.slider_background);
tray.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
tray.setGravity(Gravity.CENTER);
tray.setTextAppearance(getContext(), R.style.SliderText);
tray.setText(R.string.dismiss);
addView(tray);
// Setup the object which will be slid.
dot = new ImageView(getContext());
dot.setImageResource(R.drawable.slider_icon);
dot.setBackgroundResource(R.drawable.slider_btn);
dot.setScaleType(ScaleType.CENTER);
dot.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
dot.setPadding(30, 10, 25, 15);
addView(dot);
reset();
}
public void setOnCompleteListener(OnCompleteListener listener) {
completeListener = listener;
}
public void reset() {
tracking = false;
// Move the dot home and fade in.
if (getVisibility() != View.VISIBLE) {
dot.offsetLeftAndRight(getLeft() - dot.getLeft());
setVisibility(View.VISIBLE);
Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setDuration(FADE_MILLIS);
startAnimation(fadeIn);
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (!changed) {
return;
}
// Start the dot left-aligned.
dot.layout(0, 0, dot.getMeasuredWidth(), dot.getMeasuredHeight());
// Make the tray fill the background.
tray.layout(0, 0, getMeasuredWidth(), getMeasuredHeight());
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
tray.measure(widthMeasureSpec, heightMeasureSpec);
dot.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
heightMeasureSpec);
setMeasuredDimension(
Math.max(tray.getMeasuredWidth(), dot.getMeasuredWidth()),
Math.max(tray.getMeasuredHeight(), dot.getMeasuredHeight()));
}
private boolean withinX(View v, float x) {
if (x < v.getLeft() || x > v.getRight()) {
return false;
} else {
return true;
}
}
private boolean withinY(View v, float y) {
if (y < v.getTop() || y > v.getBottom()) {
return false;
} else {
return true;
}
}
private void slideDotHome() {
int distanceFromStart = dot.getLeft() - getLeft();
dot.offsetLeftAndRight(-distanceFromStart);
Animation slideBack = new TranslateAnimation(distanceFromStart, 0, 0, 0);
slideBack.setDuration(SLIDE_MILLIS);
slideBack.setInterpolator(new DecelerateInterpolator(SLIDE_ACCEL));
dot.startAnimation(slideBack);
}
private boolean isComplete() {
double dotCenterY = dot.getLeft() + dot.getMeasuredWidth()/2.0;
float progressPercent = (float)(dotCenterY - getLeft()) / (float)(getRight() - getLeft());
if (progressPercent > PERCENT_REQUIRED) {
return true;
} else {
return false;
}
}
private void finishSlider() {
setVisibility(View.INVISIBLE);
Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setDuration(FADE_MILLIS);
fadeOut.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationEnd(Animation animation) {
if (completeListener != null) {
completeListener.complete();
}
}
@Override
public void onAnimationRepeat(Animation animation) {}
@Override
public void onAnimationStart(Animation animation) {}
});
startAnimation(fadeOut);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
final int action = event.getAction();
final float x = event.getX();
final float y = event.getY();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Start tracking if the down event is in the dot.
tracking = withinX(dot, x) && withinY(dot, y);
return tracking || super.onTouchEvent(event);
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
// Ignore move events which did not originate in the dot.
if (!tracking) {
return super.onTouchEvent(event);
}
// The dot has been released, check to see if we've hit the threshold,
// otherwise, send the dot home.
tracking = false;
if (isComplete()) {
finishSlider();
} else {
slideDotHome();
}
return true;
case MotionEvent.ACTION_MOVE:
// Ignore move events which did not originate in the dot.
if (!tracking) {
return super.onTouchEvent(event);
}
// Update the current location.
dot.offsetLeftAndRight((int) (x - dot.getLeft() - dot.getWidth()/2.0 ));
// See if we have reached the threshold.
if (isComplete()) {
tracking = false;
finishSlider();
return true;
}
// Otherwise, we have not yet hit the completion threshold. Make sure
// the move is still within bounds of the dot and redraw.
if (!withinY(dot, y)) {
// Slid out of the slider, reset to the beginning.
tracking = false;
slideDotHome();
} else {
invalidate();
}
return true;
default:
return super.onTouchEvent(event);
}
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/Slider.java | Java | asf20 | 7,602 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import java.util.TreeMap;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
/**
* This container holds a list of all currently scheduled alarms.
* Adding/removing alarms to this container schedules/unschedules PendingIntents
* with the android AlarmManager service.
*/
public final class PendingAlarmList {
// Maps alarmId -> alarm.
private TreeMap<Long, PendingAlarm> pendingAlarms;
// Maps alarm time -> alarmId.
private TreeMap<AlarmTime, Long> alarmTimes;
private AlarmManager alarmManager;
private Context context;
public PendingAlarmList(Context context) {
pendingAlarms = new TreeMap<Long, PendingAlarm>();
alarmTimes = new TreeMap<AlarmTime, Long>();
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
this.context = context;
}
public int size() {
if (pendingAlarms.size() != alarmTimes.size()) {
throw new IllegalStateException("Inconsistent pending alarms: "
+ pendingAlarms.size() + " vs " + alarmTimes.size());
}
return pendingAlarms.size();
}
public void put(long alarmId, AlarmTime time) {
// Remove this alarm if it exists already.
remove(alarmId);
// Intents are considered equal if they have the same action, data, type,
// class, and categories. In order to schedule multiple alarms, every
// pending intent must be different. This means that we must encode
// the alarm id in the data section of the intent rather than in
// the extras bundle.
Intent notifyIntent = new Intent(context, ReceiverAlarm.class);
notifyIntent.setData(AlarmUtil.alarmIdToUri(alarmId));
PendingIntent scheduleIntent =
PendingIntent.getBroadcast(context, 0, notifyIntent, 0);
// Previous instances of this intent will be overwritten in
// the alarm manager.
alarmManager.set(AlarmManager.RTC_WAKEUP, time.calendar().getTimeInMillis(), scheduleIntent);
// Keep track of all scheduled alarms.
pendingAlarms.put(alarmId, new PendingAlarm(time, scheduleIntent));
alarmTimes.put(time, alarmId);
if (pendingAlarms.size() != alarmTimes.size()) {
throw new IllegalStateException("Inconsistent pending alarms: "
+ pendingAlarms.size() + " vs " + alarmTimes.size());
}
}
public boolean remove(long alarmId) {
PendingAlarm alarm = pendingAlarms.remove(alarmId);
if (alarm == null) {
return false;
}
Long expectedAlarmId = alarmTimes.remove(alarm.time());
alarmManager.cancel(alarm.pendingIntent());
alarm.pendingIntent().cancel();
if (expectedAlarmId != alarmId) {
throw new IllegalStateException("Internal inconsistency in PendingAlarmList");
}
if (pendingAlarms.size() != alarmTimes.size()) {
throw new IllegalStateException("Inconsistent pending alarms: "
+ pendingAlarms.size() + " vs " + alarmTimes.size());
}
return true;
}
public AlarmTime nextAlarmTime() {
if (alarmTimes.size() == 0) {
return null;
}
return alarmTimes.firstKey();
}
public AlarmTime pendingTime(long alarmId) {
PendingAlarm alarm = pendingAlarms.get(alarmId);
return alarm == null ? null : alarm.time();
}
public AlarmTime[] pendingTimes() {
AlarmTime[] times = new AlarmTime[alarmTimes.size()];
alarmTimes.keySet().toArray(times);
return times;
}
public Long[] pendingAlarms() {
Long[] alarmIds = new Long[pendingAlarms.size()];
pendingAlarms.keySet().toArray(alarmIds);
return alarmIds;
}
private class PendingAlarm {
private AlarmTime time;
private PendingIntent pendingIntent;
PendingAlarm(AlarmTime time, PendingIntent pendingIntent) {
this.time = time;
this.pendingIntent = pendingIntent;
}
public AlarmTime time() {
return time;
}
public PendingIntent pendingIntent() {
return pendingIntent;
}
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/PendingAlarmList.java | Java | asf20 | 4,764 |
package com.angrydoughnuts.android.alarmclock;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class RecevierTimeZoneChange extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, AlarmClockService.class);
i.putExtra(AlarmClockService.COMMAND_EXTRA, AlarmClockService.COMMAND_TIMEZONE_CHANGE);
context.startService(i);
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/RecevierTimeZoneChange.java | Java | asf20 | 478 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import java.lang.reflect.Field;
import android.net.Uri;
import android.provider.Settings;
public final class AlarmUtil {
static public Uri alarmIdToUri(long alarmId) {
return Uri.parse("alarm_id:" + alarmId);
}
public static long alarmUriToId(Uri uri) {
return Long.parseLong(uri.getSchemeSpecificPart());
}
enum Interval {
SECOND(1000), MINUTE(60 * 1000), HOUR(60 * 60 * 1000);
private long millis;
public long millis() { return millis; }
Interval(long millis) {
this.millis = millis;
}
}
public static long millisTillNextInterval(Interval interval) {
long now = System.currentTimeMillis();
return interval.millis() - now % interval.millis();
}
public static long nextIntervalInUTC(Interval interval) {
long now = System.currentTimeMillis();
return now + interval.millis() - now % interval.millis();
}
public static Uri getDefaultAlarmUri() {
// DEFAULT_ALARM_ALERT_URI is only available after SDK version 5.
// Fall back to the default notification if the default alarm is
// unavailable.
try {
Field f = Settings.System.class.getField("DEFAULT_ALARM_ALERT_URI");
return (Uri) f.get(null);
} catch (Exception e) {
return Settings.System.DEFAULT_NOTIFICATION_URI;
}
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/AlarmUtil.java | Java | asf20 | 2,097 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import java.util.LinkedList;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.RemoteException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
/**
* This adapter is used to query the alarm database and translate each alarm
* into a view which is displayed in a ListView.
*/
public final class AlarmViewAdapter extends ArrayAdapter<AlarmInfo> {
private AlarmClockServiceBinder service;
private LayoutInflater inflater;
private Cursor cursor;
public AlarmViewAdapter(Activity activity, DbAccessor db, AlarmClockServiceBinder service) {
super(activity, 0, new LinkedList<AlarmInfo>());
this.service = service;
this.inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.cursor = db.readAlarmInfo();
activity.startManagingCursor(cursor);
loadData();
}
private void loadData() {
while (cursor.moveToNext()) {
add(new AlarmInfo(cursor));
}
}
public void requery() {
clear();
cursor.requery();
loadData();
notifyDataSetChanged();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = inflater.inflate(R.layout.alarm_list_item, null);
TextView timeView = (TextView) view.findViewById(R.id.alarm_time);
TextView nextView = (TextView) view.findViewById(R.id.next_alarm);
TextView labelView = (TextView) view.findViewById(R.id.alarm_label);
TextView repeatView = (TextView) view.findViewById(R.id.alarm_repeat);
CheckBox enabledView = (CheckBox) view.findViewById(R.id.alarm_enabled);
final AlarmInfo info = getItem(position);
AlarmTime time = null;
// See if there is an instance of this alarm scheduled.
if (service.clock() != null) {
try {
time = service.clock().pendingAlarm(info.getAlarmId());
} catch (RemoteException e) {}
}
// If we couldn't find a pending alarm, display the configured time.
if (time == null) {
time = info.getTime();
}
String timeStr = time.localizedString(getContext());
String alarmId = "";
if (AppSettings.isDebugMode(getContext())) {
alarmId = " [" + info.getAlarmId() + "]";
}
timeView.setText(timeStr + alarmId);
enabledView.setChecked(info.enabled());
nextView.setText(time.timeUntilString(getContext()));
labelView.setText(info.getName());
if (!info.getTime().getDaysOfWeek().equals(Week.NO_REPEATS)) {
repeatView.setText(info.getTime().getDaysOfWeek().toString(getContext()));
}
enabledView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
CheckBox check = (CheckBox) v;
if (check.isChecked()) {
service.scheduleAlarm(info.getAlarmId());
requery();
} else {
service.unscheduleAlarm(info.getAlarmId());
requery();
}
}
});
return view;
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/AlarmViewAdapter.java | Java | asf20 | 3,955 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.preference.PreferenceManager;
/**
* Utility class for accessing each of the global application settings.
*/
public final class AppSettings {
// Some of these have an extra " in them because of an old copy/paste bug.
// They are forever ingrained in the settings :-(
public static final String DEBUG_MODE = "DEBUG_MODE";
public static final String NOTIFICATION_ICON = "NOTIFICATION_ICON";
public static final String LOCK_SCREEN = "LOCK_SCREEN";
public static final String CUSTOM_LOCK_SCREEN_TEXT = "CUSTOM_LOCK_SCREEN";
public static final String CUSTOM_LOCK_SCREEN_PERSISTENT = "CUSTOM_LOCK_PERSISTENT";
public static final String ALARM_TIMEOUT = "ALARM_TIMEOUT";
public static final boolean displayNotificationIcon(Context c) {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
return prefs.getBoolean(NOTIFICATION_ICON, true);
}
private static final String FORMAT_COUNTDOWN = "%c";
private static final String FORMAT_TIME = "%t";
private static final String FORMAT_BOTH = "%c (%t)";
public static final String lockScreenString(Context c, AlarmTime nextTime) {
final String[] values = c.getResources().getStringArray(R.array.lock_screen_values);
final String LOCK_SCREEN_COUNTDOWN = values[0];
final String LOCK_SCREEN_TIME = values[1];
final String LOCK_SCREEN_BOTH = values[2];
final String LOCK_SCREEN_NOTHING = values[3];
final String LOCK_SCREEN_CUSTOM = values[4];
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
final String value = prefs.getString(LOCK_SCREEN, LOCK_SCREEN_COUNTDOWN);
final String customFormat = prefs.getString(CUSTOM_LOCK_SCREEN_TEXT, FORMAT_COUNTDOWN);
// The lock screen message should be persistent iff the persistent setting
// is set AND a custom lock screen message is set.
final boolean persistent = prefs.getBoolean(CUSTOM_LOCK_SCREEN_PERSISTENT, false) && value.equals(LOCK_SCREEN_CUSTOM);
if (value.equals(LOCK_SCREEN_NOTHING)) {
return null;
}
// If no alarm is set and our lock message is not persistent, return
// a clearing string.
if (nextTime == null && !persistent) {
return "";
}
String time = "";
String countdown = "";
if (nextTime != null) {
time = nextTime.localizedString(c);
countdown = nextTime.timeUntilString(c);
}
String text;
if (value.equals(LOCK_SCREEN_COUNTDOWN)) {
text = FORMAT_COUNTDOWN;
} else if (value.equals(LOCK_SCREEN_TIME)) {
text = FORMAT_TIME;
} else if (value.equals(LOCK_SCREEN_BOTH)) {
text = FORMAT_BOTH;
} else if (value.equals(LOCK_SCREEN_CUSTOM)) {
text = customFormat;
} else {
throw new IllegalStateException("Unknown lockscreen preference: " + value);
}
text = text.replace("%t", time);
text = text.replace("%c", countdown);
return text;
}
public static final boolean isDebugMode(Context c) {
final String[] values = c.getResources().getStringArray(R.array.debug_values);
final String DEBUG_DEFAULT = values[0];
final String DEBUG_ON = values[1];
final String DEBUG_OFF = values[2];
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
final String value = prefs.getString(DEBUG_MODE, DEBUG_DEFAULT);
if (value.equals(DEBUG_ON)) {
return true;
} else if (value.equals(DEBUG_OFF)) {
return false;
} else if (value.equals(DEBUG_DEFAULT)) {
return (c.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) > 0;
} else {
throw new IllegalStateException("Unknown debug mode setting: "+ value);
}
}
public static final int alarmTimeOutMins(Context c) {
final String[] values = c.getResources().getStringArray(R.array.time_out_values);
final String ONE_MIN = values[0];
final String FIVE_MIN = values[1];
final String TEN_MIN = values[2];
final String THIRTY_MIN = values[3];
final String SIXTY_MIN = values[4];
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
final String value = prefs.getString(ALARM_TIMEOUT, TEN_MIN);
if (value.equals(ONE_MIN)) {
return 1;
} else if (value.equals(FIVE_MIN)) {
return 5;
} else if (value.equals(TEN_MIN)) {
return 10;
} else if (value.equals(THIRTY_MIN)) {
return 30;
} else if (value.equals(SIXTY_MIN)) {
return 60;
} else {
return 10;
}
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/AppSettings.java | Java | asf20 | 5,433 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import java.util.Map;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.widget.Toast;
public final class AlarmClockService extends Service {
public final static String COMMAND_EXTRA = "command";
public final static int COMMAND_UNKNOWN = 1;
public final static int COMMAND_NOTIFICATION_REFRESH = 2;
public final static int COMMAND_DEVICE_BOOT = 3;
public final static int COMMAND_TIMEZONE_CHANGE = 4;
public final static int NOTIFICATION_BAR_ID = 69;
private DbAccessor db;
private PendingAlarmList pendingAlarms;
private Notification notification;
@Override
public void onCreate() {
super.onCreate();
// Registers an exception handler of capable of writing the stack trace
// to the device's SD card. This is only possible if the proper
// permissions are available.
if (getPackageManager().checkPermission(
"android.permission.WRITE_EXTERNAL_STORAGE", getPackageName()) ==
PackageManager.PERMISSION_GRANTED) {
Thread.setDefaultUncaughtExceptionHandler(
new LoggingUncaughtExceptionHandler("/sdcard"));
}
// Access to in-memory and persistent data structures.
db = new DbAccessor(getApplicationContext());
pendingAlarms = new PendingAlarmList(getApplicationContext());
// Schedule enabled alarms during initial startup.
for (Long alarmId : db.getEnabledAlarms()) {
if (pendingAlarms.pendingTime(alarmId) != null) {
continue;
}
if (AppSettings.isDebugMode(getApplicationContext())) {
Toast.makeText(getApplicationContext(), "RENABLE " + alarmId, Toast.LENGTH_SHORT).show();
}
pendingAlarms.put(alarmId, db.readAlarmInfo(alarmId).getTime());
}
notification = new Notification(R.drawable.alarmclock_notification, null, 0);
notification.flags |= Notification.FLAG_ONGOING_EVENT;
ReceiverNotificationRefresh.startRefreshing(getApplicationContext());
}
// OnStart was depreciated in SDK 5. It is here for backwards compatibility.
// http://android-developers.blogspot.com/2010/02/service-api-changes-starting-with.html
@Override
public void onStart(Intent intent, int startId) {
handleStart(intent, startId);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleStart(intent, startId);
return START_STICKY;
}
private void handleStart(Intent intent, int startId) {
if (intent != null && intent.hasExtra(COMMAND_EXTRA)) {
Bundle extras = intent.getExtras();
int command = extras.getInt(COMMAND_EXTRA, COMMAND_UNKNOWN);
final Handler handler = new Handler();
final Runnable maybeShutdown = new Runnable() {
@Override
public void run() {
if (pendingAlarms.size() == 0) {
stopSelf();
}
}
};
switch (command) {
case COMMAND_NOTIFICATION_REFRESH:
refreshNotification();
handler.post(maybeShutdown);
break;
case COMMAND_DEVICE_BOOT:
fixPersistentSettings();
handler.post(maybeShutdown);
break;
case COMMAND_TIMEZONE_CHANGE:
if (AppSettings.isDebugMode(getApplicationContext())) {
Toast.makeText(getApplicationContext(), "TIMEZONE CHANGE, RESCHEDULING...", Toast.LENGTH_SHORT).show();
}
for (long alarmId : pendingAlarms.pendingAlarms()) {
scheduleAlarm(alarmId);
if (AppSettings.isDebugMode(getApplicationContext())) {
Toast.makeText(getApplicationContext(), "ALARM " + alarmId, Toast.LENGTH_SHORT).show();
}
}
handler.post(maybeShutdown);
break;
default:
throw new IllegalArgumentException("Unknown service command.");
}
}
}
private void refreshNotification() {
AlarmTime nextTime = pendingAlarms.nextAlarmTime();
String nextString;
if (nextTime != null) {
nextString = getString(R.string.next_alarm)
+ " " + nextTime.localizedString(getApplicationContext())
+ " (" + nextTime.timeUntilString(getApplicationContext()) + ")";
} else {
nextString = getString(R.string.no_pending_alarms);
}
// Make the notification launch the UI Activity when clicked.
final Intent notificationIntent = new Intent(this, ActivityAlarmClock.class);
final PendingIntent launch = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Context c = getApplicationContext();
notification.setLatestEventInfo(c, getString(R.string.app_name), nextString, launch);
final NotificationManager manager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (pendingAlarms.size() > 0 && AppSettings.displayNotificationIcon(c)) {
manager.notify(NOTIFICATION_BAR_ID, notification);
} else {
manager.cancel(NOTIFICATION_BAR_ID);
}
// Set the system alarm string for display on the lock screen.
String lockScreenText = AppSettings.lockScreenString(getApplicationContext(), nextTime);
if (lockScreenText != null) {
Settings.System.putString(getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED, lockScreenText);
}
}
// This hack is necessary b/c I released a version of the code with a bunch
// of errors in the settings strings. This should correct them.
public void fixPersistentSettings() {
final String badDebugName = "DEBUG_MODE\"";
final String badNotificationName = "NOTFICATION_ICON";
final String badLockScreenName = "LOCK_SCREEN\"";
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Map<String, ?> prefNames = prefs.getAll();
// Don't do anything if the bad preferences have already been fixed.
if (!prefNames.containsKey(badDebugName) &&
!prefNames.containsKey(badNotificationName) &&
!prefNames.containsKey(badLockScreenName)) {
return;
}
Editor editor = prefs.edit();
if (prefNames.containsKey(badDebugName)) {
editor.putString(AppSettings.DEBUG_MODE, prefs.getString(badDebugName, null));
editor.remove(badDebugName);
}
if (prefNames.containsKey(badNotificationName)){
editor.putBoolean(AppSettings.NOTIFICATION_ICON, prefs.getBoolean(badNotificationName, true));
editor.remove(badNotificationName);
}
if (prefNames.containsKey(badLockScreenName)) {
editor.putString(AppSettings.LOCK_SCREEN, prefs.getString(badLockScreenName, null));
editor.remove(badLockScreenName);
}
editor.commit();
}
@Override
public void onDestroy() {
super.onDestroy();
db.closeConnections();
ReceiverNotificationRefresh.stopRefreshing(getApplicationContext());
final NotificationManager manager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(NOTIFICATION_BAR_ID);
String lockScreenText = AppSettings.lockScreenString(getApplicationContext(), null);
// Only clear the lock screen if the preference is set.
if (lockScreenText != null) {
Settings.System.putString(getContentResolver(), Settings.System.NEXT_ALARM_FORMATTED, lockScreenText);
}
}
@Override
public IBinder onBind(Intent intent) {
return new AlarmClockInterfaceStub(getApplicationContext(), this);
}
@Override
public boolean onUnbind(Intent intent) {
// Decide if we need to explicitly shut down this service. Normally,
// the service would shutdown after the last un-bind, but it was explicitly
// started in onBind(). If there are no pending alarms, explicitly stop
// the service.
if (pendingAlarms.size() == 0) {
stopSelf();
return false;
}
// Returning true causes the IBinder object to be re-used until the
// service is actually shutdown.
return true;
}
public AlarmTime pendingAlarm(long alarmId) {
return pendingAlarms.pendingTime(alarmId);
}
public AlarmTime[] pendingAlarmTimes() {
return pendingAlarms.pendingTimes();
}
public void createAlarm(AlarmTime time) {
// Store the alarm in the persistent database.
long alarmId = db.newAlarm(time);
scheduleAlarm(alarmId);
}
public void deleteAlarm(long alarmId) {
pendingAlarms.remove(alarmId);
db.deleteAlarm(alarmId);
}
public void deleteAllAlarms() {
for (Long alarmId : db.getAllAlarms()) {
deleteAlarm(alarmId);
}
}
public void scheduleAlarm(long alarmId) {
AlarmInfo info = db.readAlarmInfo(alarmId);
if (info == null) {
return;
}
// Schedule the next alarm.
pendingAlarms.put(alarmId, info.getTime());
// Mark the alarm as enabled in the database.
db.enableAlarm(alarmId, true);
// Now that there is more than one pending alarm, explicitly start the
// service so that it continues to run after binding.
final Intent self = new Intent(getApplicationContext(), AlarmClockService.class);
startService(self);
refreshNotification();
}
public void acknowledgeAlarm(long alarmId) {
AlarmInfo info = db.readAlarmInfo(alarmId);
if (info == null) {
return;
}
pendingAlarms.remove(alarmId);
AlarmTime time = info.getTime();
if (time.repeats()) {
pendingAlarms.put(alarmId, time);
} else {
db.enableAlarm(alarmId, false);
}
refreshNotification();
}
public void dismissAlarm(long alarmId) {
AlarmInfo info = db.readAlarmInfo(alarmId);
if (info == null) {
return;
}
pendingAlarms.remove(alarmId);
db.enableAlarm(alarmId, false);
refreshNotification();
}
public void snoozeAlarm(long alarmId) {
snoozeAlarmFor(alarmId, db.readAlarmSettings(alarmId).getSnoozeMinutes());
}
public void snoozeAlarmFor(long alarmId, int minutes) {
// Clear the snoozed alarm.
pendingAlarms.remove(alarmId);
// Calculate the time for the next alarm.
AlarmTime time = AlarmTime.snoozeInMillisUTC(minutes);
// Schedule it.
pendingAlarms.put(alarmId, time);
refreshNotification();
}
} | 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/AlarmClockService.java | Java | asf20 | 11,332 |
package com.angrydoughnuts.android.alarmclock;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class ReceiverDeviceBoot extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// There doesn't seem to be any way to filter on the scheme-specific
// portion of the ACTION_PACKANGE_REPLACED intent (the package
// being replaced is in the ssp). Since we can't filter for it in the
// Manifest file, we get every package replaced event and cancel this
// event if it's not our package.
if (intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED)) {
if (!intent.getData().getSchemeSpecificPart().equals(context.getPackageName())) {
return;
}
}
Intent i = new Intent(context, AlarmClockService.class);
i.putExtra(AlarmClockService.COMMAND_EXTRA, AlarmClockService.COMMAND_DEVICE_BOOT);
context.startService(i);
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/ReceiverDeviceBoot.java | Java | asf20 | 984 |
package com.angrydoughnuts.android.alarmclock;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class ReceiverNotificationRefresh extends BroadcastReceiver {
public static void startRefreshing(Context context) {
context.sendBroadcast(intent(context));
}
public static void stopRefreshing(Context context) {
final AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
manager.cancel(pendingIntent(context));
}
private static Intent intent(Context context) {
return new Intent(context, ReceiverNotificationRefresh.class);
}
private static PendingIntent pendingIntent(Context context) {
return PendingIntent.getBroadcast(context, 0, intent(context), 0);
}
@Override
public void onReceive(Context context, Intent intent) {
final Intent causeRefresh = new Intent(context, AlarmClockService.class);
causeRefresh.putExtra(AlarmClockService.COMMAND_EXTRA, AlarmClockService.COMMAND_NOTIFICATION_REFRESH);
context.startService(causeRefresh);
long next = AlarmUtil.nextIntervalInUTC(AlarmUtil.Interval.MINUTE);
final AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
manager.set(AlarmManager.RTC, next, pendingIntent(context));
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/ReceiverNotificationRefresh.java | Java | asf20 | 1,396 |
package com.angrydoughnuts.android.alarmclock;
import java.util.TreeMap;
import android.content.Context;
import android.os.PowerManager;
public class WakeLock {
public static class WakeLockException extends Exception {
private static final long serialVersionUID = 1L;
public WakeLockException(String e) {
super(e);
}
}
private static final TreeMap<Long, PowerManager.WakeLock> wakeLocks =
new TreeMap<Long, PowerManager.WakeLock>();
public static final void acquire(Context context, long alarmId) throws WakeLockException {
if (wakeLocks.containsKey(alarmId)) {
throw new WakeLockException("Multiple acquisitions of wake lock for id: " + alarmId);
}
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(
PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP,
"Alarm Notification Wake Lock id " + alarmId);
wakeLock.setReferenceCounted(false);
wakeLock.acquire();
wakeLocks.put(alarmId, wakeLock);
}
public static final void assertHeld(long alarmId) throws WakeLockException {
PowerManager.WakeLock wakeLock = wakeLocks.get(alarmId);
if (wakeLock == null || !wakeLock.isHeld()) {
throw new WakeLockException("Wake lock not held for alarm id: " + alarmId);
}
}
public static final void assertAtLeastOneHeld() throws WakeLockException {
for (PowerManager.WakeLock wakeLock : wakeLocks.values()) {
if (wakeLock.isHeld()) {
return;
}
}
throw new WakeLockException("No wake locks are held.");
}
public static final void assertNoneHeld() throws WakeLockException {
for (PowerManager.WakeLock wakeLock : wakeLocks.values()) {
if (wakeLock.isHeld()) {
throw new WakeLockException("No wake locks are held.");
}
}
}
public static final void release(long alarmId) throws WakeLockException {
assertHeld(alarmId);
PowerManager.WakeLock wakeLock = wakeLocks.remove(alarmId);
wakeLock.release();
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/WakeLock.java | Java | asf20 | 2,097 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import android.content.Context;
import android.os.RemoteException;
import android.widget.Toast;
public final class AlarmClockInterfaceStub extends AlarmClockInterface.Stub {
private Context context;
private AlarmClockService service;
AlarmClockInterfaceStub(Context context, AlarmClockService service) {
this.context = context;
this.service = service;
}
@Override
public AlarmTime pendingAlarm(long alarmId) throws RemoteException {
return service.pendingAlarm(alarmId);
}
@Override
public AlarmTime[] pendingAlarmTimes() throws RemoteException {
return service.pendingAlarmTimes();
}
@Override
public void createAlarm(AlarmTime time) throws RemoteException {
debugToast("CREATE ALARM " + time.toString());
service.createAlarm(time);
}
@Override
public void deleteAlarm(long alarmId) throws RemoteException {
debugToast("DELETE ALARM " + alarmId);
service.deleteAlarm(alarmId);
}
@Override
public void deleteAllAlarms() throws RemoteException {
debugToast("DELETE ALL ALARMS");
service.deleteAllAlarms();
}
@Override
public void scheduleAlarm(long alarmId) throws RemoteException {
debugToast("SCHEDULE ALARM " + alarmId);
service.scheduleAlarm(alarmId);
}
@Override
public void unscheduleAlarm(long alarmId) {
debugToast("UNSCHEDULE ALARM " + alarmId);
service.dismissAlarm(alarmId);
}
public void acknowledgeAlarm(long alarmId) {
debugToast("ACKNOWLEDGE ALARM " + alarmId);
service.acknowledgeAlarm(alarmId);
}
@Override
public void snoozeAlarm(long alarmId) throws RemoteException {
debugToast("SNOOZE ALARM " + alarmId);
service.snoozeAlarm(alarmId);
}
@Override
public void snoozeAlarmFor(long alarmId, int minutes) throws RemoteException {
debugToast("SNOOZE ALARM " + alarmId + " for " + minutes);
service.snoozeAlarmFor(alarmId, minutes);
}
private void debugToast(String message) {
if (AppSettings.isDebugMode(context)) {
Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/AlarmClockInterfaceStub.java | Java | asf20 | 2,880 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import com.angrydoughnuts.android.alarmclock.MediaListView.OnItemPickListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Message;
import android.provider.MediaStore.Audio.Albums;
import android.provider.MediaStore.Audio.Artists;
import android.provider.MediaStore.Audio.Media;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.ViewFlipper;
import android.widget.TabHost.OnTabChangeListener;
/**
* A dialog which displays all of the audio media available on the phone.
* It allows you to access media through 4 tabs: One that lists media
* stored internally on the phone, and three that allow you to access
* the media stored on the SD card. These three tabs allow you to browse by
* artist, album, and song.
*/
public class MediaPickerDialog extends AlertDialog {
public interface OnMediaPickListener {
public void onMediaPick(String name, Uri media);
}
private final String INTERNAL_TAB = "internal";
private final String ARTISTS_TAB = "artists";
private final String ALBUMS_TAB = "albums";
private final String ALL_SONGS_TAB = "songs";
private String selectedName;
private Uri selectedUri;
private OnMediaPickListener pickListener;
private MediaPlayer mediaPlayer;
public MediaPickerDialog(final Activity context) {
super(context);
mediaPlayer = new MediaPlayer();
final LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View body_view = inflater.inflate(R.layout.media_picker_dialog, null);
setView(body_view);
TabHost tabs = (TabHost) body_view.findViewById(R.id.media_tabs);
tabs.setup();
tabs.addTab(tabs.newTabSpec(INTERNAL_TAB).setContent(R.id.media_picker_internal).setIndicator(context.getString(R.string.internal)));
tabs.addTab(tabs.newTabSpec(ARTISTS_TAB).setContent(R.id.media_picker_artists).setIndicator(context.getString(R.string.artists)));
tabs.addTab(tabs.newTabSpec(ALBUMS_TAB).setContent(R.id.media_picker_albums).setIndicator(context.getString(R.string.albums)));
tabs.addTab(tabs.newTabSpec(ALL_SONGS_TAB).setContent(R.id.media_picker_songs).setIndicator(context.getString(R.string.songs)));
final TextView lastSelected = (TextView) body_view.findViewById(R.id.media_picker_status);
final OnItemPickListener listener = new OnItemPickListener() {
@Override
public void onItemPick(Uri uri, String name) {
selectedUri = uri;
selectedName = name;
lastSelected.setText(name);
}
};
final MediaSongsView internalList = (MediaSongsView) body_view.findViewById(R.id.media_picker_internal);
internalList.setCursorManager(context);
internalList.includeDefault();
internalList.query(Media.INTERNAL_CONTENT_URI);
internalList.setMediaPlayer(mediaPlayer);
internalList.setMediaPickListener(listener);
final MediaSongsView songsList = (MediaSongsView) body_view.findViewById(R.id.media_picker_songs);
songsList.setCursorManager(context);
songsList.query(Media.EXTERNAL_CONTENT_URI);
songsList.setMediaPlayer(mediaPlayer);
songsList.setMediaPickListener(listener);
final ViewFlipper artistsFlipper = (ViewFlipper) body_view.findViewById(R.id.media_picker_artists);
final MediaArtistsView artistsList = new MediaArtistsView(context);
artistsList.setCursorManager(context);
artistsList.addToFlipper(artistsFlipper);
artistsList.query(Artists.EXTERNAL_CONTENT_URI);
artistsList.setMediaPlayer(mediaPlayer);
artistsList.setMediaPickListener(listener);
final ViewFlipper albumsFlipper = (ViewFlipper) body_view.findViewById(R.id.media_picker_albums);
final MediaAlbumsView albumsList = new MediaAlbumsView(context);
albumsList.setCursorManager(context);
albumsList.addToFlipper(albumsFlipper);
albumsList.query(Albums.EXTERNAL_CONTENT_URI);
albumsList.setMediaPlayer(mediaPlayer);
albumsList.setMediaPickListener(listener);
tabs.setOnTabChangedListener(new OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
if (tabId.equals(ARTISTS_TAB)) {
artistsFlipper.setDisplayedChild(0);
} else if (tabId.equals(ALBUMS_TAB)) {
albumsFlipper.setDisplayedChild(0);
}
}
});
super.setButton(BUTTON_POSITIVE, getContext().getString(R.string.ok),
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (selectedUri == null || pickListener == null) {
cancel();
return;
}
pickListener.onMediaPick(selectedName, selectedUri);
}
});
super.setButton(BUTTON_NEGATIVE, getContext().getString(R.string.cancel),
new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
selectedName = null;
selectedUri = null;
lastSelected.setText("");
cancel();
}
});
}
public void setPickListener(OnMediaPickListener listener) {
this.pickListener = listener;
}
@Override
protected void onStop() {
super.onStop();
mediaPlayer.stop();
}
@Override
protected void finalize() throws Throwable {
mediaPlayer.release();
super.finalize();
}
// Make these no-ops and final so the buttons can't be overridden buy the
// user nor a child.
@Override
public void setButton(CharSequence text, Message msg) { }
@Override
public final void setButton(CharSequence text, OnClickListener listener) {}
@Override
public final void setButton(int whichButton, CharSequence text, Message msg) {}
@Override
public final void setButton(int whichButton, CharSequence text, OnClickListener listener) {}
@Override
public final void setButton2(CharSequence text, Message msg) {}
@Override
public final void setButton2(CharSequence text, OnClickListener listener) {}
@Override
public final void setButton3(CharSequence text, Message msg) {}
@Override
public final void setButton3(CharSequence text, OnClickListener listener) {}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/MediaPickerDialog.java | Java | asf20 | 7,175 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import com.angrydoughnuts.android.alarmclock.MediaPickerDialog.OnMediaPickListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
/**
* This activity is used for editing alarm settings. Settings are broken
* into two pieces: alarm information and actual settings. Every alarm will
* have alarm information. Alarms will only have alarm settings if the user
* has overridden the default settings for a given alarm. This dialog is used
* to edit both the application default settings and individual alarm settings.
* When editing the application default settings, no AlarmInfo object will
* be present. When editing an alarm which hasn't yet had specific settings
* set, AlarmSettings will contain the default settings. There is one required
* EXTRA that must be supplied when starting this activity: EXTRAS_ALARM_ID,
* which should contain a long representing the alarmId of the settings
* being edited. AlarmSettings.DEFAULT_SETTINGS_ID can be used to edit the
* default settings.
*/
public final class ActivityAlarmSettings extends Activity {
public static final String EXTRAS_ALARM_ID = "alarm_id";
private final int MISSING_EXTRAS = -69;
private enum SettingType {
TIME,
NAME,
DAYS_OF_WEEK,
TONE, SNOOZE,
VIBRATE,
VOLUME_FADE;
}
private enum Dialogs {
TIME_PICKER,
NAME_PICKER,
DOW_PICKER,
TONE_PICKER,
SNOOZE_PICKER,
VOLUME_FADE_PICKER,
DELETE_CONFIRM
}
private long alarmId;
private AlarmClockServiceBinder service;
private DbAccessor db;
private AlarmInfo originalInfo;
private AlarmInfo info;
private AlarmSettings originalSettings;
private AlarmSettings settings;
SettingsAdapter settingsAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
// An alarm id is required in the extras bundle.
alarmId = getIntent().getExtras().getLong(EXTRAS_ALARM_ID, MISSING_EXTRAS);
if (alarmId == MISSING_EXTRAS) {
throw new IllegalStateException("EXTRAS_ALARM_ID not supplied in intent.");
}
// Access to in-memory and persistent data structures.
service = new AlarmClockServiceBinder(getApplicationContext());
db = new DbAccessor(getApplicationContext());
// Read the current settings from the database. Keep a copy of the
// original values so that we can write new values only if they differ
// from the originals.
originalInfo = db.readAlarmInfo(alarmId);
// Info will not be available for the default settings.
if (originalInfo != null) {
info = new AlarmInfo(originalInfo);
}
originalSettings = db.readAlarmSettings(alarmId);
settings = new AlarmSettings(originalSettings);
// Setup individual UI elements.
// Positive acknowledgment button.
final Button okButton = (Button) findViewById(R.id.settings_ok);
okButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Write AlarmInfo if it changed.
if (originalInfo != null && !originalInfo.equals(info)) {
db.writeAlarmInfo(alarmId, info);
// Explicitly enable the alarm if the user changed the time.
// This will reschedule the alarm if it was already enabled.
// It's also probably the right thing to do if the alarm wasn't
// enabled.
if (!originalInfo.getTime().equals(info.getTime())) {
service.scheduleAlarm(alarmId);
}
}
// Write AlarmSettings if they have changed.
if (!originalSettings.equals(settings)) {
db.writeAlarmSettings(alarmId, settings);
}
finish();
}
});
// Negative acknowledgment button.
final Button cancelButton = (Button) findViewById(R.id.settings_cancel);
cancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
// Delete button. Simply opens a confirmation dialog (which does the
// actual delete).
Button deleteButton = (Button) findViewById(R.id.settings_delete);
deleteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(Dialogs.DELETE_CONFIRM.ordinal());
}
});
// Setup the list of settings. Each setting is represented by a Setting
// object. Create one here for each setting type.
final ArrayList<Setting> settingsObjects =
new ArrayList<Setting>(SettingType.values().length);
// Only display AlarmInfo if the user is editing an actual alarm (as
// opposed to the default application settings).
if (alarmId != AlarmSettings.DEFAULT_SETTINGS_ID) {
// The alarm time.
settingsObjects.add(new Setting() {
@Override
public String name() { return getString(R.string.time); }
@Override
public String value() { return info.getTime().localizedString(getApplicationContext()); }
@Override
public SettingType type() { return SettingType.TIME; }
});
// A human-readable label for the alarm.
settingsObjects.add(new Setting() {
@Override
public String name() { return getString(R.string.label); }
@Override
public String value() { return info.getName().equals("") ?
getString(R.string.none) : info.getName(); }
@Override
public SettingType type() { return SettingType.NAME; }
});
// Days of the week this alarm should repeat.
settingsObjects.add(new Setting() {
@Override
public String name() { return getString(R.string.repeat); }
@Override
public String value() { return info.getTime().getDaysOfWeek().toString(getApplicationContext()); }
@Override
public SettingType type() { return SettingType.DAYS_OF_WEEK; }
});
}
// The notification tone used for this alarm.
settingsObjects.add(new Setting() {
@Override
public String name() { return getString(R.string.tone); }
@Override
public String value() {
String value = settings.getToneName();
if (AppSettings.isDebugMode(getApplicationContext())) {
value += " " + settings.getTone().toString();
}
return value;
}
@Override
public SettingType type() { return SettingType.TONE; }
});
// The snooze duration for this alarm.
settingsObjects.add(new Setting() {
@Override
public String name() { return getString(R.string.snooze_minutes); }
@Override
public String value() { return "" + settings.getSnoozeMinutes(); }
@Override
public SettingType type() { return SettingType.SNOOZE; }
});
// The vibrator setting for this alarm.
settingsObjects.add(new Setting() {
@Override
public String name() { return getString(R.string.vibrate); }
@Override
public String value() { return settings.getVibrate() ?
getString(R.string.enabled) : getString(R.string.disabled); }
@Override
public SettingType type() { return SettingType.VIBRATE; }
});
// How the volume should be controlled while this alarm is triggering.
settingsObjects.add(new Setting() {
@Override
public String name() { return getString(R.string.alarm_fade); }
@Override
public String value() { return getString(R.string.fade_description,
settings.getVolumeStartPercent(), settings.getVolumeEndPercent(),
settings.getVolumeChangeTimeSec()); }
@Override
public SettingType type() { return SettingType.VOLUME_FADE; }
});
final ListView settingsList = (ListView) findViewById(R.id.settings_list);
settingsAdapter = new SettingsAdapter(getApplicationContext(), settingsObjects);
settingsList.setAdapter(settingsAdapter);
settingsList.setOnItemClickListener(new SettingsListClickListener());
// The delete button should not be shown when editing the default settings.
if (alarmId == AlarmSettings.DEFAULT_SETTINGS_ID) {
deleteButton.setVisibility(View.GONE);
}
}
@Override
protected void onResume() {
super.onResume();
service.bind();
}
@Override
protected void onPause() {
super.onPause();
service.unbind();
}
@Override
protected void onDestroy() {
super.onDestroy();
db.closeConnections();
}
@Override
protected Dialog onCreateDialog(int id) {
switch (Dialogs.values()[id]) {
case TIME_PICKER:
final AlarmTime time = info.getTime();
int hour = time.calendar().get(Calendar.HOUR_OF_DAY);
int minute = time.calendar().get(Calendar.MINUTE);
int second = time.calendar().get(Calendar.SECOND);
return new TimePickerDialog(this, getString(R.string.time),
hour, minute, second, AppSettings.isDebugMode(this),
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(int hourOfDay, int minute, int second) {
info.setTime(new AlarmTime(hourOfDay, minute, second, time.getDaysOfWeek()));
settingsAdapter.notifyDataSetChanged();
// Destroy this dialog so that it does not save its state.
removeDialog(Dialogs.TIME_PICKER.ordinal());
}
});
case NAME_PICKER:
final View nameView = getLayoutInflater().inflate(R.layout.name_settings_dialog, null);
final TextView label = (TextView) nameView.findViewById(R.id.name_label);
label.setText(info.getName());
final AlertDialog.Builder nameBuilder = new AlertDialog.Builder(this);
nameBuilder.setTitle(R.string.alarm_label);
nameBuilder.setView(nameView);
nameBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
info.setName(label.getEditableText().toString());
settingsAdapter.notifyDataSetChanged();
dismissDialog(Dialogs.NAME_PICKER.ordinal());
}
});
nameBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismissDialog(Dialogs.NAME_PICKER.ordinal());
}
});
return nameBuilder.create();
case DOW_PICKER:
final AlertDialog.Builder dowBuilder = new AlertDialog.Builder(this);
dowBuilder.setTitle(R.string.scheduled_days);
dowBuilder.setMultiChoiceItems(
info.getTime().getDaysOfWeek().names(getApplicationContext()),
info.getTime().getDaysOfWeek().bitmask(),
new OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
info.getTime().getDaysOfWeek().addDay(Week.Day.values()[which]);
} else {
info.getTime().getDaysOfWeek().removeDay(Week.Day.values()[which]);
}
}
});
dowBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
settingsAdapter.notifyDataSetChanged();
dismissDialog(Dialogs.DOW_PICKER.ordinal());
}
});
return dowBuilder.create();
case TONE_PICKER:
MediaPickerDialog mediaPicker = new MediaPickerDialog(this);
mediaPicker.setPickListener(new OnMediaPickListener() {
@Override
public void onMediaPick(String name, Uri media) {
if (name.length() == 0) {
name = getString(R.string.unknown_name);
}
settings.setTone(media, name);
settingsAdapter.notifyDataSetChanged();
}
});
return mediaPicker;
case SNOOZE_PICKER:
// This currently imposes snooze times between 1 and 60 minutes,
// which isn't really necessary, but I think the picker is easier
// to use than a free-text field that you have to type numbers into.
final CharSequence[] items = new CharSequence[60];
// Note the array index is one-off from the value (the value of 1 is
// at index 0).
for (int i = 1; i <= 60; ++i) {
items[i-1] = new Integer(i).toString();
}
final AlertDialog.Builder snoozeBuilder = new AlertDialog.Builder(this);
snoozeBuilder.setTitle(R.string.snooze_minutes);
snoozeBuilder.setSingleChoiceItems(items, settings.getSnoozeMinutes() - 1,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
settings.setSnoozeMinutes(item + 1);
settingsAdapter.notifyDataSetChanged();
dismissDialog(Dialogs.SNOOZE_PICKER.ordinal());
}
});
return snoozeBuilder.create();
case VOLUME_FADE_PICKER:
final View fadeView = getLayoutInflater().inflate(R.layout.fade_settings_dialog, null);
final EditText volumeStart = (EditText) fadeView.findViewById(R.id.volume_start);
volumeStart.setText("" + settings.getVolumeStartPercent());
final EditText volumeEnd = (EditText) fadeView.findViewById(R.id.volume_end);
volumeEnd.setText("" + settings.getVolumeEndPercent());
final EditText volumeDuration = (EditText) fadeView.findViewById(R.id.volume_duration);
volumeDuration.setText("" + settings.getVolumeChangeTimeSec());
final AlertDialog.Builder fadeBuilder = new AlertDialog.Builder(this);
fadeBuilder.setTitle(R.string.alarm_fade);
fadeBuilder.setView(fadeView);
fadeBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
settings.setVolumeStartPercent(tryParseInt(volumeStart.getText().toString(), 0));
settings.setVolumeEndPercent(tryParseInt(volumeEnd.getText().toString(), 100));
settings.setVolumeChangeTimeSec(tryParseInt(volumeDuration.getText().toString(), 20));
settingsAdapter.notifyDataSetChanged();
dismissDialog(Dialogs.VOLUME_FADE_PICKER.ordinal());
}
});
fadeBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismissDialog(Dialogs.VOLUME_FADE_PICKER.ordinal());
}
});
return fadeBuilder.create();
case DELETE_CONFIRM:
final AlertDialog.Builder deleteConfirmBuilder = new AlertDialog.Builder(this);
deleteConfirmBuilder.setTitle(R.string.delete);
deleteConfirmBuilder.setMessage(R.string.confirm_delete);
deleteConfirmBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
service.deleteAlarm(alarmId);
dismissDialog(Dialogs.DELETE_CONFIRM.ordinal());
finish();
}
});
deleteConfirmBuilder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dismissDialog(Dialogs.DELETE_CONFIRM.ordinal());
}
});
return deleteConfirmBuilder.create();
default:
return super.onCreateDialog(id);
}
}
/**
* This is a helper class for mapping SettingType to action. Each Setting
* in the list view returns a unique SettingType. Trigger a dialog
* based off of that SettingType.
*/
private final class SettingsListClickListener implements OnItemClickListener {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final SettingsAdapter adapter = (SettingsAdapter) parent.getAdapter();
SettingType type = adapter.getItem(position).type();
switch (type) {
case TIME:
showDialog(Dialogs.TIME_PICKER.ordinal());
break;
case NAME:
showDialog(Dialogs.NAME_PICKER.ordinal());
break;
case DAYS_OF_WEEK:
showDialog(Dialogs.DOW_PICKER.ordinal());
break;
case TONE:
showDialog(Dialogs.TONE_PICKER.ordinal());
break;
case SNOOZE:
showDialog(Dialogs.SNOOZE_PICKER.ordinal());
break;
case VIBRATE:
settings.setVibrate(!settings.getVibrate());
settingsAdapter.notifyDataSetChanged();
break;
case VOLUME_FADE:
showDialog(Dialogs.VOLUME_FADE_PICKER.ordinal());
break;
}
}
}
private int tryParseInt(String input, int fallback) {
try {
return Integer.parseInt(input);
} catch (Exception e) {
return fallback;
}
}
/**
* A helper interface to encapsulate the data displayed in the list view of
* this activity. Consists of a setting name, a setting value, and a type.
* The type is used to trigger the appropriate action from the onClick
* handler.
*/
private abstract class Setting {
public abstract String name();
public abstract String value();
public abstract SettingType type();
}
/**
* This adapter populates the settings_items view with the data encapsulated
* in the individual Setting objects.
*/
private final class SettingsAdapter extends ArrayAdapter<Setting> {
public SettingsAdapter(Context context, List<Setting> settingsObjects) {
super(context, 0, settingsObjects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.settings_item, null);
TextView name = (TextView) row.findViewById(R.id.setting_name);
TextView value = (TextView) row.findViewById(R.id.setting_value);
Setting setting = getItem(position);
name.setText(setting.name());
value.setText(setting.value());
return row;
}
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/ActivityAlarmSettings.java | Java | asf20 | 19,986 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import java.util.LinkedList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public final class DbAccessor {
private DbHelper db;
private SQLiteDatabase rDb;
private SQLiteDatabase rwDb;
public DbAccessor(Context context) {
db = new DbHelper(context);
rwDb = db.getWritableDatabase();
rDb = db.getReadableDatabase();
}
public void closeConnections() {
rDb.close();
rwDb.close();
}
public long newAlarm(AlarmTime time) {
AlarmInfo info = new AlarmInfo(time, false, "");
long id = rwDb.insert(DbHelper.DB_TABLE_ALARMS, null, info.contentValues());
if (id < 0) {
throw new IllegalStateException("Unable to insert into database");
}
return id;
}
public boolean deleteAlarm(long alarmId) {
int count = rDb.delete(DbHelper.DB_TABLE_ALARMS,
DbHelper.ALARMS_COL__ID + " = " + alarmId, null);
// This may or may not exist. We don't care about the return value.
rDb.delete(DbHelper.DB_TABLE_SETTINGS,
DbHelper.SETTINGS_COL_ID + " = " + alarmId, null);
return count > 0;
}
public boolean enableAlarm(long alarmId, boolean enabled) {
ContentValues values = new ContentValues(1);
values.put(DbHelper.ALARMS_COL_ENABLED, enabled);
int count = rwDb.update(DbHelper.DB_TABLE_ALARMS, values,
DbHelper.ALARMS_COL__ID + " = " + alarmId, null);
return count != 0;
}
public List<Long> getEnabledAlarms() {
LinkedList<Long> enabled = new LinkedList<Long>();
Cursor cursor = rDb.query(DbHelper.DB_TABLE_ALARMS,
new String[] { DbHelper.ALARMS_COL__ID },
DbHelper.ALARMS_COL_ENABLED + " = 1", null, null, null, null);
while (cursor.moveToNext()) {
long alarmId = cursor.getLong(cursor.getColumnIndex(DbHelper.ALARMS_COL__ID));
enabled.add(alarmId);
}
cursor.close();
return enabled;
}
public List<Long> getAllAlarms() {
LinkedList<Long> alarms = new LinkedList<Long>();
Cursor cursor = rDb.query(DbHelper.DB_TABLE_ALARMS,
new String[] { DbHelper.ALARMS_COL__ID },
null, null, null, null, null);
while (cursor.moveToNext()) {
long alarmId = cursor.getLong(cursor.getColumnIndex(DbHelper.ALARMS_COL__ID));
alarms.add(alarmId);
}
cursor.close();
return alarms;
}
public boolean writeAlarmInfo(long alarmId, AlarmInfo info) {
return rwDb.update(DbHelper.DB_TABLE_ALARMS, info.contentValues(),
DbHelper.ALARMS_COL__ID + " = " + alarmId, null) == 1;
}
public Cursor readAlarmInfo() {
Cursor cursor = rDb.query(DbHelper.DB_TABLE_ALARMS, AlarmInfo.contentColumns(),
null, null, null, null, DbHelper.ALARMS_COL_TIME + " ASC");
return cursor;
}
public AlarmInfo readAlarmInfo(long alarmId) {
Cursor cursor = rDb.query(DbHelper.DB_TABLE_ALARMS,
AlarmInfo.contentColumns(),
DbHelper.ALARMS_COL__ID + " = " + alarmId, null, null, null, null);
if (cursor.getCount() != 1) {
cursor.close();
return null;
}
cursor.moveToFirst();
AlarmInfo info = new AlarmInfo(cursor);
cursor.close();
return info;
}
public boolean writeAlarmSettings(long alarmId, AlarmSettings settings) {
Cursor cursor = rDb.query(DbHelper.DB_TABLE_SETTINGS,
new String[] { DbHelper.SETTINGS_COL_ID },
DbHelper.SETTINGS_COL_ID + " = " + alarmId, null, null, null, null);
boolean success = false;
if (cursor.getCount() < 1) {
success = rwDb.insert(DbHelper.DB_TABLE_SETTINGS, null, settings.contentValues(alarmId)) >= 0;
} else {
success = rwDb.update(DbHelper.DB_TABLE_SETTINGS, settings.contentValues(alarmId),
DbHelper.SETTINGS_COL_ID + " = " + alarmId, null) == 1;
}
cursor.close();
return success;
}
public AlarmSettings readAlarmSettings(long alarmId) {
Cursor cursor = rDb.query(DbHelper.DB_TABLE_SETTINGS,
AlarmSettings.contentColumns(),
DbHelper.SETTINGS_COL_ID + " = " + alarmId, null, null, null, null);
if (cursor.getCount() != 1) {
cursor.close();
if (alarmId == AlarmSettings.DEFAULT_SETTINGS_ID) {
return new AlarmSettings();
}
return readAlarmSettings(AlarmSettings.DEFAULT_SETTINGS_ID);
}
AlarmSettings settings = new AlarmSettings(cursor);
cursor.close();
return settings;
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/DbAccessor.java | Java | asf20 | 5,256 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
/**
* This class contains all of the settings data for a given alarm. It also
* provides the mapping from this data to the respective columns in the
* persistent settings database.
*/
public final class AlarmSettings {
static public final long DEFAULT_SETTINGS_ID = -1;
private Uri tone;
private String toneName;
private int snoozeMinutes;
private boolean vibrate;
private int volumeStartPercent;
private int volumeEndPercent;
private int volumeChangeTimeSec;
public ContentValues contentValues(long alarmId) {
ContentValues values = new ContentValues();
values.put(DbHelper.SETTINGS_COL_ID, alarmId);
values.put(DbHelper.SETTINGS_COL_TONE_URL, tone.toString());
values.put(DbHelper.SETTINGS_COL_TONE_NAME, toneName);
values.put(DbHelper.SETTINGS_COL_SNOOZE, snoozeMinutes);
values.put(DbHelper.SETTINGS_COL_VIBRATE, vibrate);
values.put(DbHelper.SETTINGS_COL_VOLUME_STARTING, volumeStartPercent);
values.put(DbHelper.SETTINGS_COL_VOLUME_ENDING, volumeEndPercent);
values.put(DbHelper.SETTINGS_COL_VOLUME_TIME, volumeChangeTimeSec);
return values;
}
static public String[] contentColumns() {
return new String[] {
DbHelper.SETTINGS_COL_ID,
DbHelper.SETTINGS_COL_TONE_URL,
DbHelper.SETTINGS_COL_TONE_NAME,
DbHelper.SETTINGS_COL_SNOOZE,
DbHelper.SETTINGS_COL_VIBRATE,
DbHelper.SETTINGS_COL_VOLUME_STARTING,
DbHelper.SETTINGS_COL_VOLUME_ENDING,
DbHelper.SETTINGS_COL_VOLUME_TIME
};
}
public AlarmSettings() {
tone = AlarmUtil.getDefaultAlarmUri();
toneName = "Default";
snoozeMinutes = 10;
vibrate = false;
volumeStartPercent = 0;
volumeEndPercent = 100;
volumeChangeTimeSec = 20;
}
public AlarmSettings(AlarmSettings rhs) {
tone = rhs.tone;
toneName = rhs.toneName;
snoozeMinutes = rhs.snoozeMinutes;
vibrate = rhs.vibrate;
volumeStartPercent = rhs.volumeStartPercent;
volumeEndPercent = rhs.volumeEndPercent;
volumeChangeTimeSec = rhs.volumeChangeTimeSec;
}
public AlarmSettings(Cursor cursor) {
cursor.moveToFirst();
tone = Uri.parse(cursor.getString(cursor.getColumnIndex(DbHelper.SETTINGS_COL_TONE_URL)));
toneName = cursor.getString(cursor.getColumnIndex(DbHelper.SETTINGS_COL_TONE_NAME));
snoozeMinutes = cursor.getInt(cursor.getColumnIndex(DbHelper.SETTINGS_COL_SNOOZE));
vibrate = cursor.getInt(cursor.getColumnIndex(DbHelper.SETTINGS_COL_VIBRATE)) == 1;
volumeStartPercent = cursor.getInt(cursor.getColumnIndex(DbHelper.SETTINGS_COL_VOLUME_STARTING));
volumeEndPercent = cursor.getInt(cursor.getColumnIndex(DbHelper.SETTINGS_COL_VOLUME_ENDING));
volumeChangeTimeSec = cursor.getInt(cursor.getColumnIndex(DbHelper.SETTINGS_COL_VOLUME_TIME));
}
@Override
public boolean equals(Object o) {
if (!(o instanceof AlarmSettings)) {
return false;
}
AlarmSettings rhs = (AlarmSettings) o;
return tone.equals(rhs.tone)
&& toneName.equals(rhs.toneName)
&& snoozeMinutes == rhs.snoozeMinutes
&& vibrate == rhs.vibrate
&& volumeStartPercent == rhs.volumeStartPercent
&& volumeEndPercent == rhs.volumeEndPercent
&& volumeChangeTimeSec == rhs.volumeChangeTimeSec;
}
public Uri getTone() {
return tone;
}
public void setTone(Uri tone, String name) {
this.tone = tone;
this.toneName = name;
}
public String getToneName() {
return toneName;
}
public int getSnoozeMinutes() {
return snoozeMinutes;
}
public void setSnoozeMinutes(int minutes) {
if (minutes < 1) {
minutes = 1;
} else if (minutes > 60) {
minutes = 60;
}
this.snoozeMinutes = minutes;
}
public boolean getVibrate() {
return vibrate;
}
public void setVibrate(boolean vibrate) {
this.vibrate = vibrate;
}
public int getVolumeStartPercent() {
return volumeStartPercent;
}
public void setVolumeStartPercent(int volumeStartPercent) {
if (volumeStartPercent < 0) {
volumeStartPercent = 0;
} else if (volumeStartPercent > 100) {
volumeStartPercent = 100;
}
this.volumeStartPercent = volumeStartPercent;
}
public int getVolumeEndPercent() {
return volumeEndPercent;
}
public void setVolumeEndPercent(int volumeEndPercent) {
if (volumeEndPercent < 0) {
volumeEndPercent = 0;
} else if (volumeEndPercent > 100) {
volumeEndPercent = 100;
}
this.volumeEndPercent = volumeEndPercent;
}
public int getVolumeChangeTimeSec() {
return volumeChangeTimeSec;
}
public void setVolumeChangeTimeSec(int volumeChangeTimeSec) {
if (volumeChangeTimeSec < 1) {
volumeChangeTimeSec = 1;
} else if (volumeChangeTimeSec > 600) {
volumeChangeTimeSec = 600;
}
this.volumeChangeTimeSec = volumeChangeTimeSec;
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/AlarmSettings.java | Java | asf20 | 5,742 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
/**
* This is the activity responsible for alerting the user when an alarm goes
* off. It is the activity triggered by the NotificationService. It assumes
* that the intent sender has acquired a screen wake lock.
* NOTE: This class assumes that it will never be instantiated nor active
* more than once at the same time. (ie, it assumes
* android:launchMode="singleInstance" is set in the manifest file).
*/
public final class ActivityAlarmNotification extends Activity {
public final static String TIMEOUT_COMMAND = "timeout";
private enum Dialogs { TIMEOUT }
private NotificationServiceBinder notifyService;
private DbAccessor db;
private KeyguardLock screenLock;
private Handler handler;
private Runnable timeTick;
// Dialog state
int snoozeMinutes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);
db = new DbAccessor(getApplicationContext());
// Start the notification service and bind to it.
notifyService = new NotificationServiceBinder(getApplicationContext());
notifyService.bind();
// Setup a self-scheduling event loops.
handler = new Handler();
timeTick = new Runnable() {
@Override
public void run() {
notifyService.call(new NotificationServiceBinder.ServiceCallback() {
@Override
public void run(NotificationServiceInterface service) {
try {
TextView volume = (TextView) findViewById(R.id.volume);
volume.setText("Volume: " + service.volume());
} catch (RemoteException e) {}
long next = AlarmUtil.millisTillNextInterval(AlarmUtil.Interval.SECOND);
handler.postDelayed(timeTick, next);
}
});
}
};
// Setup the screen lock object. The screen will be unlocked onResume() and
// re-locked onPause();
final KeyguardManager screenLockManager =
(KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
screenLock = screenLockManager.newKeyguardLock(
"AlarmNotification screen lock");
// Setup individual UI elements.
final Button snoozeButton = (Button) findViewById(R.id.notify_snooze);
snoozeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
notifyService.acknowledgeCurrentNotification(snoozeMinutes);
finish();
}
});
final Button decreaseSnoozeButton = (Button) findViewById(R.id.notify_snooze_minus_five);
decreaseSnoozeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int snooze = snoozeMinutes - 5;
if (snooze < 5) {
snooze = 5;
}
snoozeMinutes = snooze;
redraw();
}
});
final Button increaseSnoozeButton = (Button) findViewById(R.id.notify_snooze_plus_five);
increaseSnoozeButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int snooze = snoozeMinutes + 5;
if (snooze > 60) {
snooze = 60;
}
snoozeMinutes = snooze;
redraw();
}
});
final Slider dismiss = (Slider) findViewById(R.id.dismiss_slider);
dismiss.setOnCompleteListener(new Slider.OnCompleteListener() {
@Override
public void complete() {
notifyService.acknowledgeCurrentNotification(0);
finish();
}
});
}
@Override
protected void onResume() {
super.onResume();
screenLock.disableKeyguard();
handler.post(timeTick);
redraw();
}
@Override
protected void onPause() {
super.onPause();
handler.removeCallbacks(timeTick);
screenLock.reenableKeyguard();
}
@Override
protected void onDestroy() {
super.onDestroy();
db.closeConnections();
notifyService.unbind();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Bundle extras = intent.getExtras();
if (extras == null || extras.getBoolean(TIMEOUT_COMMAND, false) == false) {
return;
}
// The notification service has signaled this activity for a second time.
// This represents a acknowledgment timeout. Display the appropriate error.
// (which also finish()es this activity.
showDialog(Dialogs.TIMEOUT.ordinal());
}
@Override
protected Dialog onCreateDialog(int id) {
switch (Dialogs.values()[id]) {
case TIMEOUT:
final AlertDialog.Builder timeoutBuilder = new AlertDialog.Builder(this);
timeoutBuilder.setIcon(android.R.drawable.ic_dialog_alert);
timeoutBuilder.setTitle(R.string.time_out_title);
timeoutBuilder.setMessage(R.string.time_out_error);
timeoutBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {}
});
AlertDialog dialog = timeoutBuilder.create();
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
finish();
}});
return dialog;
default:
return super.onCreateDialog(id);
}
}
private final void redraw() {
notifyService.call(new NotificationServiceBinder.ServiceCallback() {
@Override
public void run(NotificationServiceInterface service) {
long alarmId;
try {
alarmId = service.currentAlarmId();
} catch (RemoteException e) {
return;
}
AlarmInfo alarmInfo = db.readAlarmInfo(alarmId);
if (snoozeMinutes == 0) {
snoozeMinutes = db.readAlarmSettings(alarmId).getSnoozeMinutes();
}
String info = alarmInfo.getTime().toString() + "\n" + alarmInfo.getName();
if (AppSettings.isDebugMode(getApplicationContext())) {
info += " [" + alarmId + "]";
findViewById(R.id.volume).setVisibility(View.VISIBLE);
} else {
findViewById(R.id.volume).setVisibility(View.GONE);
}
TextView infoText = (TextView) findViewById(R.id.alarm_info);
infoText.setText(info);
TextView snoozeInfo = (TextView) findViewById(R.id.notify_snooze_time);
snoozeInfo.setText(getString(R.string.snooze) + "\n"
+ getString(R.string.minutes, snoozeMinutes));
}
});
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/ActivityAlarmNotification.java | Java | asf20 | 7,786 |
package com.angrydoughnuts.android.alarmclock;
import java.util.Calendar;
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
public class Week implements Parcelable {
public static final Week NO_REPEATS = new Week(new boolean[] {false, false, false, false, false, false, false});
public static final Week EVERYDAY = new Week(new boolean[] {true, true, true, true, true, true, true});
public static final Week WEEKDAYS = new Week(new boolean[] {false, true, true, true, true, true, false});
public static final Week WEEKENDS = new Week(new boolean[] {true, false, false, false, false, false, true});
public enum Day {
SUN(R.string.dow_sun),
MON(R.string.dow_mon),
TUE(R.string.dow_tue),
WED(R.string.dow_wed),
THU(R.string.dow_thu),
FRI(R.string.dow_fri),
SAT(R.string.dow_sat);
private int stringId;
Day (int stringId) {
this.stringId = stringId;
}
public int stringId() {
return stringId;
}
}
private boolean[] bitmask;
public Week(Parcel source) {
bitmask = source.createBooleanArray();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeBooleanArray(bitmask);
}
public Week() {
bitmask = new boolean[Day.values().length];
}
public Week(Week rhs) {
bitmask = rhs.bitmask.clone();
}
public Week(boolean[] bitmask) {
if (bitmask.length != Day.values().length) {
throw new IllegalArgumentException("Wrong sized bitmask: " + bitmask.length);
}
this.bitmask = bitmask;
}
public boolean[] bitmask() {
return bitmask;
}
public void addDay(Day day) {
bitmask[day.ordinal()] = true;
}
public void removeDay(Day day) {
bitmask[day.ordinal()] = false;
}
public boolean hasDay(Day day) {
return bitmask[day.ordinal()];
}
public CharSequence[] names(Context context) {
CharSequence[] nameList = new CharSequence[Day.values().length];
for (Day day : Day.values()) {
nameList[day.ordinal()] = context.getString(day.stringId());
}
return nameList;
}
public String toString(Context context) {
if (this.equals(NO_REPEATS)) {
return context.getString(R.string.no_repeats);
}
if (this.equals(EVERYDAY)) {
return context.getString(R.string.everyday);
}
if (this.equals(WEEKDAYS)) {
return context.getString(R.string.weekdays);
}
if (this.equals(WEEKENDS)) {
return context.getString(R.string.weekends);
}
String list = "";
for (Day day : Day.values()) {
if (!bitmask[day.ordinal()]) {
continue;
}
switch (day) {
case SUN:
list += " " + context.getString(R.string.dow_sun_short);
break;
case MON:
list += " " + context.getString(R.string.dow_mon_short);
break;
case TUE:
list += " " + context.getString(R.string.dow_tue_short);
break;
case WED:
list += " " + context.getString(R.string.dow_wed_short);
break;
case THU:
list += " " + context.getString(R.string.dow_thu_short);
break;
case FRI:
list += " " + context.getString(R.string.dow_fri_short);
break;
case SAT:
list += " " + context.getString(R.string.dow_sat_short);
break;
}
}
return list;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Week)) {
return false;
}
Week rhs = (Week) o;
if (bitmask.length != rhs.bitmask.length) {
return false;
}
for (Day day : Day.values()) {
if (bitmask[day.ordinal()] != rhs.bitmask[day.ordinal()]) {
return false;
}
}
return true;
}
@Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<Week> CREATOR =
new Parcelable.Creator<Week>() {
@Override
public Week createFromParcel(Parcel source) {
return new Week(source);
}
@Override
public Week[] newArray(int size) {
return new Week[size];
}
};
public static Day calendarToDay(int dow) {
int ordinalOffset = dow - Calendar.SUNDAY;
return Day.values()[ordinalOffset];
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/Week.java | Java | asf20 | 4,273 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import java.util.LinkedList;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
public class NotificationServiceBinder {
private Context context;
private NotificationServiceInterface notify;
private LinkedList<ServiceCallback> callbacks;
NotificationServiceBinder(Context context) {
this.context = context;
this.callbacks = new LinkedList<ServiceCallback>();
}
public void bind() {
final Intent serviceIntent = new Intent(context, NotificationService.class);
if (!context.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE)) {
throw new IllegalStateException("Unable to bind to NotificationService.");
}
}
public void unbind() {
context.unbindService(serviceConnection);
notify = null;
}
public interface ServiceCallback {
void run(NotificationServiceInterface service);
}
final private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
notify = NotificationServiceInterface.Stub.asInterface(service);
while (callbacks.size() > 0) {
ServiceCallback callback = callbacks.remove();
callback.run(notify);
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
notify = null;
}
};
public void call(ServiceCallback callback) {
if (notify != null) {
callback.run(notify);
} else {
callbacks.offer(callback);
}
}
public void acknowledgeCurrentNotification(final int snoozeMinutes) {
call(new ServiceCallback() {
@Override
public void run(NotificationServiceInterface service) {
try {
service.acknowledgeCurrentNotification(snoozeMinutes);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/NotificationServiceBinder.java | Java | asf20 | 2,821 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import java.util.Calendar;
import com.angrydoughnuts.android.alarmclock.Week.Day;
import android.content.ContentValues;
import android.database.Cursor;
/**
* This class contains the data that represents an alarm. That is, a unique
* numeric identifier, a time, whether or not it's enabled, and a configured
* name. It also provides a mapping to and from the respective columns in
* the alarm database for each of these pieces of data.
*/
public final class AlarmInfo {
private long alarmId;
private AlarmTime time;
private boolean enabled;
private String name;
public AlarmInfo(Cursor cursor) {
alarmId = cursor.getLong(cursor.getColumnIndex(DbHelper.ALARMS_COL__ID));
enabled = cursor.getInt(cursor.getColumnIndex(DbHelper.ALARMS_COL_ENABLED)) == 1;
name = cursor.getString(cursor.getColumnIndex(DbHelper.ALARMS_COL_NAME));
int secondsAfterMidnight = cursor.getInt(cursor.getColumnIndex(DbHelper.ALARMS_COL_TIME));
int dowBitmask = cursor.getInt(cursor.getColumnIndex(DbHelper.ALARMS_COL_DAY_OF_WEEK));
time = BuildAlarmTime(secondsAfterMidnight, dowBitmask);
}
public AlarmInfo(AlarmTime time, boolean enabled, String name) {
alarmId = -69; // initially invalid.
this.time = time;
this.enabled = enabled;
this.name = name;
}
public AlarmInfo(AlarmInfo rhs) {
alarmId = rhs.alarmId;
time = new AlarmTime(rhs.time);
enabled = rhs.enabled;
name = rhs.name;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof AlarmInfo)) {
return false;
}
AlarmInfo rhs = (AlarmInfo) o;
return alarmId == rhs.alarmId
&& time.equals(rhs.time)
&& enabled == rhs.enabled
&& name.equals(rhs.name);
}
public ContentValues contentValues() {
ContentValues values = new ContentValues();
values.put(DbHelper.ALARMS_COL_TIME, TimeToInteger(time));
values.put(DbHelper.ALARMS_COL_ENABLED, enabled);
values.put(DbHelper.ALARMS_COL_NAME, name);
values.put(DbHelper.ALARMS_COL_DAY_OF_WEEK, WeekToInteger(time));
return values;
}
static public String[] contentColumns() {
return new String[] {
DbHelper.ALARMS_COL__ID,
DbHelper.ALARMS_COL_TIME,
DbHelper.ALARMS_COL_ENABLED,
DbHelper.ALARMS_COL_NAME,
DbHelper.ALARMS_COL_DAY_OF_WEEK
};
}
public long getAlarmId() {
return alarmId;
}
public AlarmTime getTime() {
return time;
}
public void setTime(AlarmTime time) {
this.time = time;
}
public boolean enabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private static int TimeToInteger(AlarmTime time) {
Calendar c = time.calendar();
int hourOfDay = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
int second = c.get(Calendar.SECOND);
return hourOfDay * 3600 + minute * 60 + second;
}
private static int WeekToInteger(AlarmTime time) {
boolean[] bitmask = time.getDaysOfWeek().bitmask();
int dowBitmask = 0;
for (Day day: Day.values()) {
if (bitmask[day.ordinal()]) {
dowBitmask |= 1 << day.ordinal();
}
}
return dowBitmask;
}
private static AlarmTime BuildAlarmTime(int secondsAfterMidnight, int dowBitmask) {
int hours = secondsAfterMidnight % 3600;
int minutes = (secondsAfterMidnight - (hours * 3600)) % 60;
int seconds = (secondsAfterMidnight- (hours * 3600 + minutes * 60));
Week week = new Week();
for (Day day : Day.values()) {
if ((dowBitmask & 1 << day.ordinal()) > 0) {
week.addDay(day);
}
}
return new AlarmTime(hours, minutes, seconds, week);
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/AlarmInfo.java | Java | asf20 | 4,609 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* An exception handler that writes the stact trace to a file on the
* device's SD card. Make sure that the WRITE_EXTERNAL_STORAGE permission
* is available before using his class.
* NOTE: Mostly lifted from:
* http://stackoverflow.com/questions/601503/how-do-i-obtain-crash-data-from-my-android-application
*/
public final class LoggingUncaughtExceptionHandler implements UncaughtExceptionHandler {
private String directory;
private UncaughtExceptionHandler defaultHandler;
public LoggingUncaughtExceptionHandler(String directory) {
this.directory = directory;
this.defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
try {
String timestamp = new SimpleDateFormat("yyyyMMdd_kkmmss.SSSS").format(Calendar.getInstance().getTime());
String filename = timestamp + "-alarmclock.txt";
Writer stacktrace = new StringWriter();
ex.printStackTrace(new PrintWriter(stacktrace));
BufferedWriter bos = new BufferedWriter(new FileWriter(directory + "/" + filename));
bos.write(stacktrace.toString());
bos.flush();
bos.close();
stacktrace.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
defaultHandler.uncaughtException(thread, ex);
}
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/LoggingUncaughtExceptionHandler.java | Java | asf20 | 2,398 |
package com.angrydoughnuts.android.alarmclock;
import com.angrydoughnuts.android.alarmclock.WakeLock.WakeLockException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
public class ReceiverAlarm extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent recvIntent) {
Uri alarmUri = recvIntent.getData();
long alarmId = AlarmUtil.alarmUriToId(alarmUri);
try {
WakeLock.acquire(context, alarmId);
} catch (WakeLockException e) {
if (AppSettings.isDebugMode(context)) {
throw new IllegalStateException(e.getMessage());
}
}
Intent notifyService = new Intent(context, NotificationService.class);
notifyService.setData(alarmUri);
context.startService(notifyService);
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/ReceiverAlarm.java | Java | asf20 | 843 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import java.util.LinkedList;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
/**
* This class is a wrapper for the process of binding to the AlarmClockService.
* It provides a seemingly synchronous semantic for the asynchronous binding
* process. If the service is not properly bound, a callback is created and
* registered to be run as soon as binding successfully completes. Call
* bind() and unbind() to trigger these processes.
*/
public class AlarmClockServiceBinder {
private Context context;
private AlarmClockInterface clock;
private LinkedList<ServiceCallback> callbacks;
public AlarmClockServiceBinder(Context context) {
this.context = context;
this.callbacks = new LinkedList<ServiceCallback>();
}
public AlarmClockInterface clock() {
return clock;
}
public void bind() {
final Intent serviceIntent = new Intent(context, AlarmClockService.class);
if (!context.bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE)) {
throw new IllegalStateException("Unable to bind to AlarmClockService.");
}
}
public void unbind() {
context.unbindService(serviceConnection);
clock = null;
}
private interface ServiceCallback {
void run() throws RemoteException;
}
final private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
clock = AlarmClockInterface.Stub.asInterface(service);
while (callbacks.size() > 0) {
ServiceCallback callback = callbacks.remove();
try {
callback.run();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
clock = null;
}
};
private void runOrDefer(ServiceCallback callback) {
if (clock != null) {
try {
callback.run();
} catch (RemoteException e) {
e.printStackTrace();
}
} else {
callbacks.offer(callback);
}
}
public void createAlarm(final AlarmTime time) {
runOrDefer(new ServiceCallback() {
@Override
public void run() throws RemoteException {
clock.createAlarm(time);
}
});
}
public void deleteAlarm(final long alarmId) {
runOrDefer(new ServiceCallback() {
@Override
public void run() throws RemoteException {
clock.deleteAlarm(alarmId);
}
});
}
public void deleteAllAlarms() {
runOrDefer(new ServiceCallback() {
@Override
public void run() throws RemoteException {
clock.deleteAllAlarms();
}
});
}
public void scheduleAlarm(final long alarmId) {
runOrDefer(new ServiceCallback() {
@Override
public void run() throws RemoteException {
clock.scheduleAlarm(alarmId);
}
});
}
public void unscheduleAlarm(final long alarmId) {
runOrDefer(new ServiceCallback() {
@Override
public void run() throws RemoteException {
clock.unscheduleAlarm(alarmId);
}
});
}
public void acknowledgeAlarm(final long alarmId) {
runOrDefer(new ServiceCallback() {
@Override
public void run() throws RemoteException {
clock.acknowledgeAlarm(alarmId);
}
});
}
public void snoozeAlarm(final long alarmId) {
runOrDefer(new ServiceCallback() {
@Override
public void run() throws RemoteException {
clock.snoozeAlarm(alarmId);
}
});
}
public void snoozeAlarmFor(final long alarmId, final int minutes) {
runOrDefer(new ServiceCallback() {
@Override
public void run() throws RemoteException {
clock.snoozeAlarmFor(alarmId, minutes);
}
});
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/AlarmClockServiceBinder.java | Java | asf20 | 4,736 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import com.angrydoughnuts.android.alarmclock.Week.Day;
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.format.DateFormat;
/**
* A class that encapsulates an alarm time. It represents a time between 00:00
* and 23:59. It also contains a list of days on which this alarm should be
* rescheduled. If no days are listed, the alarm is only scheduled once
* per time it is enabled. The class is Parcelable so that it can be
* returned as an object from the AlarmClockService and is Comparable so that
* an ordered list can be created in PendingAlarmList.
*/
public final class AlarmTime implements Parcelable, Comparable<AlarmTime> {
private Calendar calendar;
private Week daysOfWeek;
/**
* Copy constructor.
* @param rhs
*/
public AlarmTime(AlarmTime rhs) {
calendar = (Calendar) rhs.calendar.clone();
daysOfWeek = new Week(rhs.daysOfWeek);
}
/**
* Construct an AlarmTime for the next occurrence of this hour/minute/second.
* It will not repeat.
* @param hourOfDay
* @param minute
* @param second
*/
public AlarmTime(int hourOfDay, int minute, int second) {
this(hourOfDay, minute, second, new Week());
}
/**
* Construct an AlarmTime for the next occurrence of this hour/minute/second
* which occurs on the specified days of the week.
* @param hourOfDay
* @param minute
* @param second
* @param daysOfWeek
*/
public AlarmTime(int hourOfDay, int minute, int second, Week daysOfWeek) {
this.calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);
this.daysOfWeek = daysOfWeek;
findNextOccurrence();
}
private void findNextOccurrence() {
Calendar now = Calendar.getInstance();
// If this hour/minute/second has already occurred today, move to tomorrow.
if (calendar.before(now)) {
calendar.add(Calendar.DATE, 1);
}
if (calendar.before(now)) {
throw new IllegalStateException("Inconsistent calendar.");
}
// If there are no repeats requested, there is nothing left to do.
if (daysOfWeek.equals(Week.NO_REPEATS)) {
return;
}
// Keep incrementing days until we hit a suitable day of the week.
for (int i = 0; i < Day.values().length; ++i) {
Day alarmDay = Week.calendarToDay(calendar.get(Calendar.DAY_OF_WEEK));
if (daysOfWeek.hasDay(alarmDay)) {
return;
}
calendar.add(Calendar.DATE, 1);
}
throw new IllegalStateException("Didn't find a suitable date for alarm.");
}
@Override
public int compareTo(AlarmTime another) {
return calendar.compareTo(another.calendar);
}
@Override
public boolean equals(Object o) {
if (!(o instanceof AlarmTime)) {
return false;
}
AlarmTime rhs = (AlarmTime) o;
if (!calendar.equals(rhs.calendar)) {
return false;
}
return this.daysOfWeek.equals(rhs.daysOfWeek);
}
public String toString() {
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm.ss MMMM dd yyyy");
return formatter.format(calendar.getTimeInMillis());
}
public String localizedString(Context context) {
boolean is24HourFormat = DateFormat.is24HourFormat(context);
String format = "";
String second = "";
if (AppSettings.isDebugMode(context)) {
second = ".ss";
}
if (is24HourFormat) {
format = "HH:mm" + second;
} else {
format = "h:mm" + second + " aaa";
}
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.format(calendar.getTime());
}
public Calendar calendar() {
return calendar;
}
public Week getDaysOfWeek() {
return daysOfWeek;
}
public boolean repeats() {
return !daysOfWeek.equals(Week.NO_REPEATS);
}
public String timeUntilString(Context c) {
Calendar now = Calendar.getInstance();
if (calendar.before(now)) {
return c.getString(R.string.alarm_has_occurred);
}
long now_min = now.getTimeInMillis() / 1000 / 60;
long then_min = calendar.getTimeInMillis() / 1000 / 60;
long difference_minutes = then_min - now_min;
long days = difference_minutes / (60 * 24);
long hours = difference_minutes % (60 * 24);
long minutes = hours % 60;
hours = hours / 60;
String value = "";
if (days == 1) {
value += c.getString(R.string.day, days) + " ";
} else if (days > 1) {
value += c.getString(R.string.days, days) + " ";
}
if (hours == 1) {
value += c.getString(R.string.hour, hours) + " ";
} else if (hours > 1) {
value += c.getString(R.string.hours, hours) + " ";
}
if (minutes == 1) {
value += c.getString(R.string.minute, minutes) + " ";
} else if (minutes > 1) {
value += c.getString(R.string.minutes, minutes) + " ";
}
return value;
}
/**
* A static method which generates an AlarmTime object @minutes in the future.
* It first truncates seconds (rounds down to the nearest minute) before
* adding @minutes
* @param minutes
* @return
*/
public static AlarmTime snoozeInMillisUTC(int minutes) {
Calendar snooze = Calendar.getInstance();
snooze.set(Calendar.SECOND, 0);
snooze.add(Calendar.MINUTE, minutes);
return new AlarmTime(
snooze.get(Calendar.HOUR_OF_DAY),
snooze.get(Calendar.MINUTE),
snooze.get(Calendar.SECOND));
}
private AlarmTime(Parcel source) {
this.calendar = (Calendar) source.readSerializable();
this.daysOfWeek = source.readParcelable(null);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeSerializable(calendar);
dest.writeParcelable(daysOfWeek, 0);
}
public static final Parcelable.Creator<AlarmTime> CREATOR =
new Parcelable.Creator<AlarmTime>() {
@Override
public AlarmTime createFromParcel(Parcel source) {
return new AlarmTime(source);
}
@Override
public AlarmTime[] newArray(int size) {
return new AlarmTime[size];
}
};
@Override
public int describeContents() {
return 0;
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/AlarmTime.java | Java | asf20 | 7,065 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public final class DbHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "alarmclock";
public static final int DB_VERSION = 1;
public static final String DB_TABLE_ALARMS = "alarms";
public static final String ALARMS_COL__ID = "_id";
public static final String ALARMS_COL_TIME = "time";
public static final String ALARMS_COL_ENABLED = "enabled";
public static final String ALARMS_COL_NAME = "name";
public static final String ALARMS_COL_DAY_OF_WEEK = "dow";
public static final String DB_TABLE_SETTINGS = "settings";
public static final String SETTINGS_COL_ID = "id";
public static final String SETTINGS_COL_TONE_URL = "tone_url";
public static final String SETTINGS_COL_TONE_NAME = "tone_name";
public static final String SETTINGS_COL_SNOOZE = "snooze";
public static final String SETTINGS_COL_VIBRATE = "vibrate";
public static final String SETTINGS_COL_VOLUME_STARTING = "vol_start";
public static final String SETTINGS_COL_VOLUME_ENDING = "vol_end";
public static final String SETTINGS_COL_VOLUME_TIME = "vol_time";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// Alarm metadata table:
// |(auto primary) | (0 to 86399) | (boolean) | (string) | (bitmask(7)) |
// | _id | time | enabled | name | dow |
// time is seconds past midnight.
db.execSQL("CREATE TABLE " + DB_TABLE_ALARMS + " ("
+ ALARMS_COL__ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ ALARMS_COL_NAME + " TEXT, "
+ ALARMS_COL_DAY_OF_WEEK + " UNSIGNED INTEGER (0, 127), "
+ ALARMS_COL_TIME + " UNSIGNED INTEGER (0, 86399),"
+ ALARMS_COL_ENABLED + " UNSIGNED INTEGER (0, 1))");
// |(primary) | (string) | (string) | (1 to 60) | (boolean) | (0 to 100) | (0 to 100) | (0 to 60) |
// | id | tone_url | tone_name | snooze | vibrate | vol_start | vol_end | vol_time |
// snooze is in minutes.
db.execSQL("CREATE TABLE " + DB_TABLE_SETTINGS + " ("
+ SETTINGS_COL_ID + " INTEGER PRIMARY KEY, "
+ SETTINGS_COL_TONE_URL + " TEXT,"
+ SETTINGS_COL_TONE_NAME + " TEXT,"
+ SETTINGS_COL_SNOOZE + " UNSIGNED INTEGER (1, 60),"
+ SETTINGS_COL_VIBRATE + " UNSIGNED INTEGER (0, 1),"
+ SETTINGS_COL_VOLUME_STARTING + " UNSIGNED INTEGER (1, 100),"
+ SETTINGS_COL_VOLUME_ENDING + " UNSIGNED INTEGER (1, 100),"
+ SETTINGS_COL_VOLUME_TIME + " UNSIGNED INTEGER (1, 60))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
| 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/DbHelper.java | Java | asf20 | 3,591 |
/****************************************************************************
* Copyright 2010 kraigs.android@gmail.com
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
****************************************************************************/
package com.angrydoughnuts.android.alarmclock;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.MergeCursor;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SimpleCursorAdapter.ViewBinder;
/**
* An extension to the ListView widget specialized for selecting audio media.
* Use one of the concrete implementations MediaSongsView, MediaArtistsView
* or MediaAlbumsView.
*/
public class MediaListView extends ListView implements OnItemClickListener {
public interface OnItemPickListener {
public void onItemPick(Uri uri, String name);
}
protected static int DEFAULT_TONE_INDEX = -69;
private Cursor cursor;
private Cursor staticCursor;
private MediaPlayer mPlayer;
private ViewFlipper flipper;
private Activity cursorManager;
private Uri contentUri;
private String nameColumn;
private String sortOrder;
private OnItemPickListener listener;
private String selectedName;
private Uri selectedUri;
public MediaListView(Context context) {
this(context, null);
}
public MediaListView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MediaListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setChoiceMode(CHOICE_MODE_SINGLE);
setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (flipper == null || flipper.getDisplayedChild() == 0) {
return false;
}
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (event.getAction() == KeyEvent.ACTION_UP) {
if (mPlayer != null) {
mPlayer.stop();
}
flipper.setInAnimation(getContext(), R.anim.slide_in_right);
flipper.setOutAnimation(getContext(), R.anim.slide_out_right);
flipper.showPrevious();
}
return true;
}
return false;
}
});
}
public void setMediaPlayer(MediaPlayer mPlayer) {
this.mPlayer = mPlayer;
}
protected MediaPlayer getMediaPlayer() {
return mPlayer;
}
public void addToFlipper(ViewFlipper flipper) {
this.flipper = flipper;
flipper.setAnimateFirstView(false);
flipper.addView(this);
}
protected ViewFlipper getFlipper() {
return flipper;
}
public void setCursorManager(Activity activity) {
this.cursorManager = activity;
}
protected void manageCursor(Cursor cursor) {
cursorManager.startManagingCursor(cursor);
}
protected void query(Uri contentUri, String nameColumn,
int rowResId, String[] displayColumns, int[] resIDs) {
query(contentUri, nameColumn, null, rowResId, displayColumns, resIDs);
}
protected void query(Uri contentUri, String nameColumn, String selection,
int rowResId, String[] displayColumns, int[] resIDs) {
this.nameColumn = nameColumn;
final ArrayList<String> queryColumns =
new ArrayList<String>(displayColumns.length + 1);
queryColumns.addAll(Arrays.asList(displayColumns));
// The ID column is required for the SimpleCursorAdapter. Make sure to
// add it if it's not already there.
if (!queryColumns.contains(BaseColumns._ID)) {
queryColumns.add(BaseColumns._ID);
}
Cursor dbCursor = getContext().getContentResolver().query(
contentUri, queryColumns.toArray(new String[] {}),
selection, null, sortOrder);
if (staticCursor != null) {
Cursor[] cursors = new Cursor[] { staticCursor, dbCursor };
cursor = new MergeCursor(cursors);
} else {
cursor = dbCursor;
}
manageCursor(cursor);
this.contentUri = contentUri;
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(
getContext(), rowResId, cursor, displayColumns, resIDs);
// Use a custom binder to highlight the selected element.
adapter.setViewBinder(new ViewBinder() {
@Override
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (view.getVisibility() == View.VISIBLE && view instanceof TextView) {
TextView text = (TextView) view;
if (isItemChecked(cursor.getPosition())) {
text.setTypeface(Typeface.DEFAULT_BOLD);
} else {
text.setTypeface(Typeface.DEFAULT);
}
}
// Let the default binder do the real work.
return false;
}});
setAdapter(adapter);
setOnItemClickListener(this);
}
public void overrideSortOrder(String sortOrder) {
this.sortOrder = sortOrder;
}
protected void includeStaticCursor(Cursor cursor) {
staticCursor = cursor;
}
// TODO(cgallek): get rid of these two accessor methods in favor of
// onClick callbacks.
public String getLastSelectedName() {
return selectedName;
}
public Uri getLastSelectedUri() {
return selectedUri;
}
public void setMediaPickListener(OnItemPickListener listener) {
this.listener = listener;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
setItemChecked(position, true);
cursor.moveToPosition(position);
selectedName = cursor.getString(cursor.getColumnIndex(nameColumn));
final int toneIndex = cursor.getInt(cursor.getColumnIndex(BaseColumns._ID));
if (toneIndex == DEFAULT_TONE_INDEX) {
selectedUri = AlarmUtil.getDefaultAlarmUri();
} else {
selectedUri = Uri.withAppendedPath(contentUri, "" + toneIndex);
}
if (listener != null) {
listener.onItemPick(selectedUri, selectedName);
}
}
} | 0indri0-1111 | android/alarmclock/src/com/angrydoughnuts/android/alarmclock/MediaListView.java | Java | asf20 | 6,853 |
/*
Copyright 2012 Mattias Jiderhamn
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package se.jiderhamn.classloader.leak.prevention;
import java.beans.PropertyEditorManager;
import java.lang.management.ManagementFactory;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Authenticator;
import java.net.URL;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
/** Changed by Christopher Kohlhaas
* Modified from the original uncommented the following line
* //java.awt.Toolkit.getDefaultToolkit(); // Will start a Thread
* //javax.imageio.ImageIO.getCacheDirectory(); // Will call sun.awt.AppContext.getAppContext()
* and added the JettyRemover
*/
/**
* This class helps prevent classloader leaks.
* <h1>Basic setup</h1>
* <p>Activate protection by adding this class as a context listener
* in your <code>web.xml</code>, like this:</p>
* <pre>
* <listener>
* <listener-class>se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor</listener-class>
* </listener>
* </pre>
*
* You should usually declare this <code>listener</code> before any other listeners, to make it "outermost".
*
* <h1>Configuration</h1>
* The context listener has a number of settings that can be configured with context parameters in <code>web.xml</code>,
* i.e.:
*
* <pre>
* <context-param>
* <param-name>ClassLoaderLeakPreventor.stopThreads</param-name>
* <param-value>false</param-value>
* </context-param>
* </pre>
*
* The available settings are
* <table border="1">
* <tr>
* <th>Parameter name</th>
* <th>Default value</th>
* <th>Description</th>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.stopThreads</code></td>
* <td><code>true</code></td>
* <td>Should threads tied to the web app classloader be forced to stop at application shutdown?</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.stopTimerThreads</code></td>
* <td><code>true</code></td>
* <td>Should Timer threads tied to the web app classloader be forced to stop at application shutdown?</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.executeShutdownHooks</td>
* <td><code>true</code></td>
* <td>Should shutdown hooks registered from the application be executed at application shutdown?</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.threadWaitMs</td>
* <td><code>5000</code> (5 seconds)</td>
* <td>No of milliseconds to wait for threads to finish execution, before stopping them.</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.shutdownHookWaitMs</code></td>
* <td><code>10000</code> (10 seconds)</td>
* <td>
* No of milliseconds to wait for shutdown hooks to finish execution, before stopping them.
* If set to -1 there will be no waiting at all, but Thread is allowed to run until finished.
* </td>
* </tr>
* </table>
*
*
* <h1>License</h1>
* <p>This code is licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2</a> license,
* which allows you to include modified versions of the code in your distributed software, without having to release
* your source code.</p>
*
* <h1>More info</h1>
* <p>For more info, see
* <a href="http://java.jiderhamn.se/2012/03/04/classloader-leaks-vi-this-means-war-leak-prevention-library/">here</a>.
* </p>
*
* <h1>Design goals</h1>
* <p>If you want to help improve this component, you should be aware of the design goals</p>
* <p>
* Primary design goal: Zero dependencies. The component should build and run using nothing but the JDK and the
* Servlet API. Specifically we should <b>not</b> depend on any logging framework, since they are part of the problem.
* We also don't want to use any utility libraries, in order not to impose any further dependencies into any project
* that just wants to get rid of classloader leaks.
* Access to anything outside of the standard JDK (in order to prevent a known leak) should be managed
* with reflection.
* </p>
* <p>
* Secondary design goal: Keep the runtime component in a single <code>.java</code> file. It should be possible to
* just add this one <code>.java</code> file into your own source tree.
* </p>
*
* @author Mattias Jiderhamn, 2012-2013
*/
public class ClassLoaderLeakPreventor implements javax.servlet.ServletContextListener {
/** Default no of milliseconds to wait for threads to finish execution */
public static final int THREAD_WAIT_MS_DEFAULT = 5 * 1000; // 5 seconds
/** Default no of milliseconds to wait for shutdown hook to finish execution */
public static final int SHUTDOWN_HOOK_WAIT_MS_DEFAULT = 10 * 1000; // 10 seconds
public static final String JURT_ASYNCHRONOUS_FINALIZER = "com.sun.star.lib.util.AsynchronousFinalizer";
///////////
// Settings
/** Should threads tied to the web app classloader be forced to stop at application shutdown? */
protected boolean stopThreads = true;
/** Should Timer threads tied to the web app classloader be forced to stop at application shutdown? */
protected boolean stopTimerThreads = true;
/** Should shutdown hooks registered from the application be executed at application shutdown? */
protected boolean executeShutdownHooks = true;
/**
* No of milliseconds to wait for threads to finish execution, before stopping them.
*/
protected int threadWaitMs = SHUTDOWN_HOOK_WAIT_MS_DEFAULT;
/**
* No of milliseconds to wait for shutdown hooks to finish execution, before stopping them.
* If set to -1 there will be no waiting at all, but Thread is allowed to run until finished.
*/
protected int shutdownHookWaitMs = SHUTDOWN_HOOK_WAIT_MS_DEFAULT;
/** Is it possible, that we are running under JBoss? */
private boolean mayBeJBoss = false;
protected final Field java_lang_Thread_threadLocals;
protected final Field java_lang_Thread_inheritableThreadLocals;
protected final Field java_lang_ThreadLocal$ThreadLocalMap_table;
protected Field java_lang_ThreadLocal$ThreadLocalMap$Entry_value;
public ClassLoaderLeakPreventor() {
// Initialize some reflection variables
java_lang_Thread_threadLocals = findField(Thread.class, "threadLocals");
java_lang_Thread_inheritableThreadLocals = findField(Thread.class, "inheritableThreadLocals");
java_lang_ThreadLocal$ThreadLocalMap_table = findFieldOfClass("java.lang.ThreadLocal$ThreadLocalMap", "table");
if(java_lang_Thread_threadLocals == null)
error("java.lang.Thread.threadLocals not found; something is seriously wrong!");
if(java_lang_Thread_inheritableThreadLocals == null)
error("java.lang.Thread.inheritableThreadLocals not found; something is seriously wrong!");
if(java_lang_ThreadLocal$ThreadLocalMap_table == null)
error("java.lang.ThreadLocal$ThreadLocalMap.table not found; something is seriously wrong!");
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Implement javax.servlet.ServletContextListener
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
public void contextInitialized(ServletContextEvent servletContextEvent) {
final ServletContext servletContext = servletContextEvent.getServletContext();
stopThreads = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopThreads"));
stopTimerThreads = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopTimerThreads"));
executeShutdownHooks = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.executeShutdownHooks"));
threadWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.threadWaitMs", THREAD_WAIT_MS_DEFAULT);
shutdownHookWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.shutdownHookWaitMs", SHUTDOWN_HOOK_WAIT_MS_DEFAULT);
info("Settings for " + this.getClass().getName() + " (CL: 0x" +
Integer.toHexString(System.identityHashCode(getWebApplicationClassLoader())) + "):");
info(" stopThreads = " + stopThreads);
info(" stopTimerThreads = " + stopTimerThreads);
info(" executeShutdownHooks = " + executeShutdownHooks);
info(" threadWaitMs = " + threadWaitMs + " ms");
info(" shutdownHookWaitMs = " + shutdownHookWaitMs + " ms");
final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
try {
// If package org.jboss is found, we may be running under JBoss
mayBeJBoss = (contextClassLoader.getResource("org/jboss") != null);
}
catch(Exception ex) {
// Do nothing
}
info("Initializing context by loading some known offenders with system classloader");
// This part is heavily inspired by Tomcats JreMemoryLeakPreventionListener
// See http://svn.apache.org/viewvc/tomcat/trunk/java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java?view=markup
try {
// Switch to system classloader in before we load/call some JRE stuff that will cause
// the current classloader to be available for garbage collection
Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
// Christopher: Uncommented as it will not work on some containers as google app engine
//java.awt.Toolkit.getDefaultToolkit(); // Will start a Thread
java.security.Security.getProviders();
java.sql.DriverManager.getDrivers(); // Load initial drivers using system classloader
// Christopher: Uncommented as it will not work on some containers as google app engine
//javax.imageio.ImageIO.getCacheDirectory(); // Will call sun.awt.AppContext.getAppContext()
try {
Class.forName("javax.security.auth.Policy")
.getMethod("getPolicy")
.invoke(null);
}
catch (IllegalAccessException iaex) {
error(iaex);
}
catch (InvocationTargetException itex) {
error(itex);
}
catch (NoSuchMethodException nsmex) {
error(nsmex);
}
catch (ClassNotFoundException e) {
// Ignore silently - class is deprecated
}
try {
javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
}
catch (Exception ex) { // Example: ParserConfigurationException
error(ex);
}
try {
Class.forName("javax.xml.bind.DatatypeConverterImpl"); // Since JDK 1.6. May throw java.lang.Error
}
catch (ClassNotFoundException e) {
// Do nothing
}
try {
Class.forName("javax.security.auth.login.Configuration", true, ClassLoader.getSystemClassLoader());
}
catch (ClassNotFoundException e) {
// Do nothing
}
// This probably does not affect classloaders, but prevents some problems with .jar files
try {
// URL needs to be well-formed, but does not need to exist
new URL("jar:file://dummy.jar!/").openConnection().setDefaultUseCaches(false);
}
catch (Exception ex) {
error(ex);
}
/////////////////////////////////////////////////////
// Load Sun specific classes that may cause leaks
final boolean isSunJRE = System.getProperty("java.vendor").startsWith("Sun");
try {
Class.forName("com.sun.jndi.ldap.LdapPoolManager");
}
catch(ClassNotFoundException cnfex) {
if(isSunJRE)
error(cnfex);
}
try {
Class.forName("sun.java2d.Disposer"); // Will start a Thread
}
catch (ClassNotFoundException cnfex) {
if(isSunJRE && ! mayBeJBoss) // JBoss blocks this package/class, so don't warn
error(cnfex);
}
try {
Class<?> gcClass = Class.forName("sun.misc.GC");
final Method requestLatency = gcClass.getDeclaredMethod("requestLatency", long.class);
requestLatency.invoke(null, 3600000L);
}
catch (ClassNotFoundException cnfex) {
if(isSunJRE)
error(cnfex);
}
catch (NoSuchMethodException nsmex) {
error(nsmex);
}
catch (IllegalAccessException iaex) {
error(iaex);
}
catch (InvocationTargetException itex) {
error(itex);
}
// Cause oracle.jdbc.driver.OracleTimeoutPollingThread to be started with contextClassLoader = system classloader
try {
Class.forName("oracle.jdbc.driver.OracleTimeoutThreadPerVM");
} catch (ClassNotFoundException e) {
// Ignore silently - class not present
}
}
catch (Throwable ex)
{
error( ex);
}
finally {
// Reset original classloader
Thread.currentThread().setContextClassLoader(contextClassLoader);
}
}
@SuppressWarnings("unchecked")
public void contextDestroyed(ServletContextEvent servletContextEvent) {
final boolean jvmIsShuttingDown = isJvmShuttingDown();
if(jvmIsShuttingDown) {
info("JVM is shutting down - skip cleanup");
return; // Don't do anything more
}
info(getClass().getName() + " shutting down context by removing known leaks (CL: 0x" +
Integer.toHexString(System.identityHashCode(getWebApplicationClassLoader())) + ")");
//////////////////
// Fix known leaks
//////////////////
java.beans.Introspector.flushCaches(); // Clear cache of strong references
// Apache Commons Pool can leave unfinished threads. Anything specific we can do?
clearBeanELResolverCache();
fixBeanValidationApiLeak();
fixJsfLeak();
fixGeoToolsLeak();
// Can we do anything about Google Guice ?
// Can we do anything about Groovy http://jira.codehaus.org/browse/GROOVY-4154 ?
clearIntrospectionUtilsCache();
// Can we do anything about Logback http://jira.qos.ch/browse/LBCORE-205 ?
// Force the execution of the cleanup code for JURT; see https://issues.apache.org/ooo/show_bug.cgi?id=122517
forceStartOpenOfficeJurtCleanup();
////////////////////
// Fix generic leaks
// Deregister JDBC drivers contained in web application
deregisterJdbcDrivers();
// Unregister MBeans loaded by the web application class loader
unregisterMBeans();
// Deregister shutdown hooks - execute them immediately
deregisterShutdownHooks();
deregisterPropertyEditors();
deregisterSecurityProviders();
clearDefaultAuthenticator();
deregisterRmiTargets();
clearThreadLocalsOfAllThreads();
stopThreads();
destroyThreadGroups();
unsetCachedKeepAliveTimer();
try {
try { // First try Java 1.6 method
final Method clearCache16 = ResourceBundle.class.getMethod("clearCache", ClassLoader.class);
debug("Since Java 1.6+ is used, we can call " + clearCache16);
clearCache16.invoke(null, getWebApplicationClassLoader());
}
catch (NoSuchMethodException e) {
// Not Java 1.6+, we have to clear manually
final Map<?,?> cacheList = getStaticFieldValue(ResourceBundle.class, "cacheList"); // Java 5: SoftCache extends AbstractMap
final Iterator<?> iter = cacheList.keySet().iterator();
Field loaderRefField = null;
while(iter.hasNext()) {
Object key = iter.next(); // CacheKey
if(loaderRefField == null) { // First time
loaderRefField = key.getClass().getDeclaredField("loaderRef");
loaderRefField.setAccessible(true);
}
WeakReference<ClassLoader> loaderRef = (WeakReference<ClassLoader>) loaderRefField.get(key); // LoaderReference extends WeakReference
ClassLoader classLoader = loaderRef.get();
if(isWebAppClassLoaderOrChild(classLoader)) {
info("Removing ResourceBundle from cache: " + key);
iter.remove();
}
}
}
}
catch(Exception ex) {
error(ex);
}
// (CacheKey of java.util.ResourceBundle.NONEXISTENT_BUNDLE will point to first referring classloader...)
// Release this classloader from Apache Commons Logging (ACL) by calling
// LogFactory.release(getCurrentClassLoader());
// Use reflection in case ACL is not present.
// Do this last, in case other shutdown procedures want to log something.
final Class logFactory = findClass("org.apache.commons.logging.LogFactory");
if(logFactory != null) { // Apache Commons Logging present
info("Releasing web app classloader from Apache Commons Logging");
try {
logFactory.getMethod("release", java.lang.ClassLoader.class)
.invoke(null, getWebApplicationClassLoader());
}
catch (Exception ex) {
error(ex);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Fix generic leaks
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** Deregister JDBC drivers loaded by web app classloader */
public void deregisterJdbcDrivers() {
final List<Driver> driversToDeregister = new ArrayList<Driver>();
final Enumeration<Driver> allDrivers = DriverManager.getDrivers();
while(allDrivers.hasMoreElements()) {
final Driver driver = allDrivers.nextElement();
if(isLoadedInWebApplication(driver)) // Should be true for all returned by DriverManager.getDrivers()
driversToDeregister.add(driver);
}
for(Driver driver : driversToDeregister) {
try {
warn("JDBC driver loaded by web app deregistered: " + driver.getClass());
DriverManager.deregisterDriver(driver);
}
catch (SQLException e) {
error(e);
}
}
}
/** Unregister MBeans loaded by the web application class loader */
protected void unregisterMBeans() {
try {
JettyJMXRemover jettyJMXRemover = null;
// If you enable jmx support in jetty 8 or 9 some mbeans (e.g. for the servletholder or sessionmanager) are instanciated in the web application thread
// and a reference to the WebappClassloader is stored in a private ObjectMBean._loader which is unfortunatly not the classloader that loaded the class.
// So for unregisterMBeans to work even for the jetty mbeans we need to access the MBeanContainer class of the jetty container.
try {
jettyJMXRemover = new JettyJMXRemover(getWebApplicationClassLoader());
} catch (Exception ex) {
error( ex);
}
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
final Set<ObjectName> allMBeanNames = mBeanServer.queryNames(new ObjectName("*:*"), null);
for(ObjectName objectName : allMBeanNames) {
try {
if ( jettyJMXRemover != null && jettyJMXRemover.unregisterJettyJMXBean(objectName))
{
continue;
}
final ClassLoader mBeanClassLoader = mBeanServer.getClassLoaderFor(objectName);
if(isWebAppClassLoaderOrChild(mBeanClassLoader)) { // MBean loaded in web application
warn("MBean '" + objectName + "' was loaded in web application; unregistering");
mBeanServer.unregisterMBean(objectName);
}
}
catch(Exception e) { // MBeanRegistrationException / InstanceNotFoundException
error(e);
}
}
}
catch (Exception e) { // MalformedObjectNameException
error(e);
}
}
/**
* removes the ObjectMBean beans created by the jetty MBeanContainer for each webapp context such as
* Mbeans for SessionHandler,ServletHandler and ServletMappings
*/
private class JettyJMXRemover
{
Object[] objectsWrappedWithMBean;
Object beanContainer;
private Method findBeanM;
private Method removeBeanM;
@SuppressWarnings("unchecked")
public JettyJMXRemover(ClassLoader classLoader) throws Exception
{
try
{
// If package org.eclipse.jetty is found, we may be running under jetty
if (classLoader.getResource("org/eclipse/jetty") == null)
{
return;
}
}
catch(Exception ex) {
return;
}
// Jetty not started with jmx or webappcontext so an unregister of webappcontext JMX beans is not neccessary.
try {
Class.forName("org.eclipse.jetty.jmx.MBeanContainer", false, classLoader.getParent());
Class.forName("org.eclipse.jetty.webapp.WebAppContext", false, classLoader.getParent());
}
catch (Exception e1) {
return;
}
// first we need to access the necessary classes via reflection (are all loaded, because webapplication is already initialized)
final Class WebAppClassLoaderC = Class.forName("org.eclipse.jetty.webapp.WebAppClassLoader");
final Class WebAppContextC = Class.forName("org.eclipse.jetty.webapp.WebAppContext");
final Class ServerC = Class.forName("org.eclipse.jetty.server.Server");
final Class SessionHandlerC = Class.forName("org.eclipse.jetty.server.session.SessionHandler");
final Class MBeanContainerC = Class.forName("org.eclipse.jetty.jmx.MBeanContainer");
final Class SessionManagerC = Class.forName("org.eclipse.jetty.server.SessionManager");
final Class ServletHandlerC = Class.forName("org.eclipse.jetty.servlet.ServletHandler");
// first we need access to the MBeanContainer to access the beans
//WebAppContext webappContext = (WebAppContext)servletContext;
final Object webappContext = WebAppClassLoaderC.getMethod("getContext").invoke(classLoader);
if (webappContext == null)
{
return;
}
//Server server = (Server)webappContext.getServer();
final Object server = WebAppContextC.getMethod("getServer").invoke(webappContext);
if ( server == null)
{
return;
}
//MBeanContainer beanContainer = (MBeanContainer)server.getBean( MBeanContainer.class);
beanContainer = ServerC.getMethod("getBean", Class.class).invoke( server, MBeanContainerC);
findBeanM = MBeanContainerC.getMethod("findBean", ObjectName.class);
removeBeanM = MBeanContainerC.getMethod("removeBean", Object.class);
// now we store all objects that belong to the webapplication and that will be wrapped by mbeans in a list
if ( beanContainer !=null )
{
List list = new ArrayList();
//SessionHandler sessionHandler =webappContext.getSessionHandler();
final Object sessionHandler = WebAppContextC.getMethod("getSessionHandler").invoke( webappContext);
if (sessionHandler != null)
{
list.add( sessionHandler);
//SessionManager sessionManager = sessionHandler.getSessionManager();
final Object sessionManager = SessionHandlerC.getMethod("getSessionManager").invoke( sessionHandler);
if ( sessionManager != null)
{
list.add( sessionManager);
//SessionIdManager sessionIdManager = sessionManager.getSessionIdManager();
final Object sessionIdManager = SessionManagerC.getMethod("getSessionIdManager").invoke( sessionManager);
if (sessionIdManager != null)
{
list.add( sessionIdManager);
}
}
}
//SecurityHandler securityHandler = webappContext.getSecurityHandler();
final Object securityHandler = WebAppContextC.getMethod("getSecurityHandler").invoke( webappContext);
if ( securityHandler != null )
{
list.add( securityHandler);
}
//ServletHandler servletHandler = webappContext.getServletHandler();
final Object servletHandler = WebAppContextC.getMethod("getServletHandler").invoke( webappContext);
if ( servletHandler != null)
{
list.add( servletHandler );
//Object[] servletMappings = servletHandler.getServletMappings();
final Object[] servletMappings = (Object[]) ServletHandlerC.getMethod("getServletMappings").invoke( servletHandler);
list.addAll( Arrays.asList(servletMappings ));
//Object[] servlets = servletHandler.getServlets();
final Object[] servlets = (Object[]) ServletHandlerC.getMethod("getServlets").invoke( servletHandler);
list.addAll( Arrays.asList(servlets ));
}
this.objectsWrappedWithMBean = list.toArray();
}
}
boolean unregisterJettyJMXBean(ObjectName objectName)
{
if ( objectsWrappedWithMBean == null || objectName.getDomain() == null || !objectName.getDomain().contains("org.eclipse.jetty"))
{
return false;
}
else
{
try
{
Object obj = findBeanM.invoke(beanContainer, objectName);
// look if obj is in the suspect list
for ( Object o: objectsWrappedWithMBean)
{
if ( o == obj)
{
warn("MBean '" + objectName + "' is a suspect in causing memory leaks; unregistering");
// and remove it via the MBeanContainer
removeBeanM.invoke(beanContainer, obj);
return true;
}
}
}
catch (Exception ex) {
error( ex);
}
return false;
}
}
}
/** Find and deregister shutdown hooks. Will by default execute the hooks after removing them. */
protected void deregisterShutdownHooks() {
// We will not remove known shutdown hooks, since loading the owning class of the hook,
// may register the hook if previously unregistered
@SuppressWarnings("unchecked")
Map<Thread, Thread> shutdownHooks = (Map<Thread, Thread>) getStaticFieldValue("java.lang.ApplicationShutdownHooks", "hooks");
if(shutdownHooks != null) { // Could be null during JVM shutdown, which we already avoid, but be extra precautious
// Iterate copy to avoid ConcurrentModificationException
for(Thread shutdownHook : new ArrayList<Thread>(shutdownHooks.keySet())) {
if(isThreadInWebApplication(shutdownHook)) { // Planned to run in web app
removeShutdownHook(shutdownHook);
}
}
}
}
/** Deregister shutdown hook and execute it immediately */
@SuppressWarnings("deprecation")
protected void removeShutdownHook(Thread shutdownHook) {
final String displayString = "'" + shutdownHook + "' of type " + shutdownHook.getClass().getName();
error("Removing shutdown hook: " + displayString);
Runtime.getRuntime().removeShutdownHook(shutdownHook);
if(executeShutdownHooks) { // Shutdown hooks should be executed
info("Executing shutdown hook now: " + displayString);
// Make sure it's from this web app instance
shutdownHook.start(); // Run cleanup immediately
if(shutdownHookWaitMs > 0) { // Wait for shutdown hook to finish
try {
shutdownHook.join(shutdownHookWaitMs); // Wait for thread to run
}
catch (InterruptedException e) {
// Do nothing
}
if(shutdownHook.isAlive()) {
warn(shutdownHook + "still running after " + shutdownHookWaitMs + " ms - Stopping!");
shutdownHook.stop();
}
}
}
}
/** Deregister custom property editors */
protected void deregisterPropertyEditors() {
final Field registryField = findField(PropertyEditorManager.class, "registry");
if(registryField == null) {
info("Internal registry of " + PropertyEditorManager.class.getName() + " not found");
}
else {
try {
synchronized (PropertyEditorManager.class) {
@SuppressWarnings("unchecked")
final Map<Class<?>, Class<?>> registry = (Map<Class<?>, Class<?>>) registryField.get(null);
if(registry != null) { // Initialized
final Set<Class> toRemove = new HashSet<Class>();
for(Map.Entry<Class<?>, Class<?>> entry : registry.entrySet()) {
if(isLoadedByWebApplication(entry.getKey()) ||
isLoadedByWebApplication(entry.getValue())) { // More likely
toRemove.add(entry.getKey());
}
}
for(Class clazz : toRemove) {
warn("Property editor for type " + clazz + " = " + registry.get(clazz) + " needs to be deregistered");
PropertyEditorManager.registerEditor(clazz, null); // Deregister
}
}
}
}
catch (Exception e) { // Such as IllegalAccessException
error(e);
}
}
}
/** Deregister custom security providers */
protected void deregisterSecurityProviders() {
final Set<String> providersToRemove = new HashSet<String>();
for(java.security.Provider provider : java.security.Security.getProviders()) {
if(isLoadedInWebApplication(provider)) {
providersToRemove.add(provider.getName());
}
}
if(! providersToRemove.isEmpty()) {
warn("Removing security providers loaded in web app: " + providersToRemove);
for(String providerName : providersToRemove) {
java.security.Security.removeProvider(providerName);
}
}
}
/** Clear the default java.net.Authenticator (in case current one is loaded in web app) */
protected void clearDefaultAuthenticator() {
final Authenticator defaultAuthenticator = getStaticFieldValue(Authenticator.class, "theAuthenticator");
if(defaultAuthenticator == null || // Can both mean not set, or error retrieving, so unset anyway to be safe
isLoadedInWebApplication(defaultAuthenticator)) {
Authenticator.setDefault(null);
}
}
/** This method is heavily inspired by org.apache.catalina.loader.WebappClassLoader.clearReferencesRmiTargets() */
protected void deregisterRmiTargets() {
try {
final Class objectTableClass = findClass("sun.rmi.transport.ObjectTable");
if(objectTableClass != null) {
clearRmiTargetsMap((Map<?, ?>) getStaticFieldValue(objectTableClass, "objTable"));
clearRmiTargetsMap((Map<?, ?>) getStaticFieldValue(objectTableClass, "implTable"));
}
}
catch (Exception ex) {
error(ex);
}
}
/** Iterate RMI Targets Map and remove entries loaded by web app classloader */
protected void clearRmiTargetsMap(Map<?, ?> rmiTargetsMap) {
try {
final Field cclField = findFieldOfClass("sun.rmi.transport.Target", "ccl");
debug("Looping " + rmiTargetsMap.size() + " RMI Targets to find leaks");
for(Iterator<?> iter = rmiTargetsMap.values().iterator(); iter.hasNext(); ) {
Object target = iter.next(); // sun.rmi.transport.Target
ClassLoader ccl = (ClassLoader) cclField.get(target);
if(isWebAppClassLoaderOrChild(ccl)) {
warn("Removing RMI Target: " + target);
iter.remove();
}
}
}
catch (Exception ex) {
error(ex);
}
}
protected void clearThreadLocalsOfAllThreads() {
final ThreadLocalProcessor clearingThreadLocalProcessor = new ClearingThreadLocalProcessor();
for(Thread thread : getAllThreads()) {
forEachThreadLocalInThread(thread, clearingThreadLocalProcessor);
}
}
/**
* Partially inspired by org.apache.catalina.loader.WebappClassLoader.clearReferencesThreads()
*/
@SuppressWarnings("deprecation")
protected void stopThreads() {
final Class<?> workerClass = findClass("java.util.concurrent.ThreadPoolExecutor$Worker");
final Field oracleTarget = findField(Thread.class, "target"); // Sun/Oracle JRE
final Field ibmRunnable = findField(Thread.class, "runnable"); // IBM JRE
for(Thread thread : getAllThreads()) {
final Runnable runnable = (oracleTarget != null) ?
(Runnable) getFieldValue(oracleTarget, thread) : // Sun/Oracle JRE
(Runnable) getFieldValue(ibmRunnable, thread); // IBM JRE
if(thread != Thread.currentThread() && // Ignore current thread
(isThreadInWebApplication(thread) || isLoadedInWebApplication(runnable))) {
if (thread.getClass().getName().startsWith(JURT_ASYNCHRONOUS_FINALIZER)) {
// Note, the thread group of this thread may be "system" if it is triggered by the Garbage Collector
// however if triggered by us in forceStartOpenOfficeJurtCleanup() it may depend on the application server
if(stopThreads) {
info("Found JURT thread " + thread.getName() + "; starting " + JURTKiller.class.getSimpleName());
new JURTKiller(thread).start();
}
else
warn("JURT thread " + thread.getName() + " is still running in web app");
}
else if(thread.getThreadGroup() != null &&
("system".equals(thread.getThreadGroup().getName()) || // System thread
"RMI Runtime".equals(thread.getThreadGroup().getName()))) { // RMI thread (honestly, just copied from Tomcat)
if("Keep-Alive-Timer".equals(thread.getName())) {
thread.setContextClassLoader(getWebApplicationClassLoader().getParent());
debug("Changed contextClassLoader of HTTP keep alive thread");
}
}
else if(thread.isAlive()) { // Non-system, running in web app
if("java.util.TimerThread".equals(thread.getClass().getName())) {
if(stopTimerThreads) {
warn("Stopping Timer thread running in classloader.");
stopTimerThread(thread);
}
else {
info("Timer thread is running in classloader, but will not be stopped");
}
}
else {
// If threads is running an java.util.concurrent.ThreadPoolExecutor.Worker try shutting down the executor
if(workerClass != null && workerClass.isInstance(runnable)) {
if(stopThreads) {
warn("Shutting down " + ThreadPoolExecutor.class.getName() + " running within the classloader.");
try {
// java.util.concurrent.ThreadPoolExecutor, introduced in Java 1.5
final Field workerExecutor = findField(workerClass, "this$0");
final ThreadPoolExecutor executor = getFieldValue(workerExecutor, runnable);
executor.shutdownNow();
}
catch (Exception ex) {
error(ex);
}
}
else
info(ThreadPoolExecutor.class.getName() + " running within the classloader will not be shut down.");
}
final String displayString = "'" + thread + "' of type " + thread.getClass().getName();
if(stopThreads) {
final String waitString = (threadWaitMs > 0) ? "after " + threadWaitMs + " ms " : "";
warn("Stopping Thread " + displayString + " running in web app " + waitString);
if(threadWaitMs > 0) {
try {
thread.join(threadWaitMs); // Wait for thread to run
}
catch (InterruptedException e) {
// Do nothing
}
}
// Normally threads should not be stopped (method is deprecated), since it may cause an inconsistent state.
// In this case however, the alternative is a classloader leak, which may or may not be considered worse.
if(thread.isAlive())
thread.stop();
}
else {
warn("Thread " + displayString + " is still running in web app");
}
}
}
}
}
}
protected void stopTimerThread(Thread thread) {
// Seems it is not possible to access Timer of TimerThread, so we need to mimic Timer.cancel()
/**
try {
Timer timer = (Timer) findField(thread.getClass(), "this$0").get(thread); // This does not work!
warn("Cancelling Timer " + timer + " / TimeThread '" + thread + "'");
timer.cancel();
}
catch (IllegalAccessException iaex) {
error(iaex);
}
*/
try {
final Field newTasksMayBeScheduled = findField(thread.getClass(), "newTasksMayBeScheduled");
final Object queue = findField(thread.getClass(), "queue").get(thread); // java.lang.TaskQueue
final Method clear = queue.getClass().getDeclaredMethod("clear");
clear.setAccessible(true);
// Do what java.util.Timer.cancel() does
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (queue) {
newTasksMayBeScheduled.set(thread, false);
clear.invoke(queue);
queue.notify(); // "In case queue was already empty."
}
// We shouldn't need to join() here, thread will finish soon enough
}
catch (Exception ex) {
error(ex);
}
}
/** Destroy any ThreadGroups that are loaded by the application classloader */
public void destroyThreadGroups() {
try {
ThreadGroup systemThreadGroup = Thread.currentThread().getThreadGroup();
while(systemThreadGroup.getParent() != null) {
systemThreadGroup = systemThreadGroup.getParent();
}
// systemThreadGroup should now be the topmost ThreadGroup, "system"
int enumeratedGroups;
ThreadGroup[] allThreadGroups;
int noOfGroups = systemThreadGroup.activeGroupCount(); // Estimate no of groups
do {
noOfGroups += 10; // Make room for 10 extra
allThreadGroups = new ThreadGroup[noOfGroups];
enumeratedGroups = systemThreadGroup.enumerate(allThreadGroups);
} while(enumeratedGroups >= noOfGroups); // If there was not room for all groups, try again
for(ThreadGroup threadGroup : allThreadGroups) {
if(isLoadedInWebApplication(threadGroup) && ! threadGroup.isDestroyed()) {
warn("ThreadGroup '" + threadGroup + "' was loaded inside application, needs to be destroyed");
int noOfThreads = threadGroup.activeCount();
if(noOfThreads > 0) {
warn("There seems to be " + noOfThreads + " running in ThreadGroup '" + threadGroup + "'; interrupting");
try {
threadGroup.interrupt();
}
catch (Exception e) {
error(e);
}
}
try {
threadGroup.destroy();
info("ThreadGroup '" + threadGroup + "' successfully destroyed");
}
catch (Exception e) {
error(e);
}
}
}
}
catch (Exception ex) {
error(ex);
}
}
/**
* Since Keep-Alive-Timer thread may have terminated, but still be referenced, we need to make sure it does not
* reference this classloader.
*/
protected void unsetCachedKeepAliveTimer() {
Object keepAliveCache = getStaticFieldValue("sun.net.www.http.HttpClient", "kac", true);
if(keepAliveCache != null) {
final Thread keepAliveTimer = getFieldValue(keepAliveCache, "keepAliveTimer");
if(keepAliveTimer != null) {
if(isWebAppClassLoaderOrChild(keepAliveTimer.getContextClassLoader())) {
keepAliveTimer.setContextClassLoader(getWebApplicationClassLoader().getParent());
error("ContextClassLoader of sun.net.www.http.HttpClient cached Keep-Alive-Timer set to parent instead");
}
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Fix specific leaks
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** Clean the cache of BeanELResolver */
protected void clearBeanELResolverCache() {
final Class beanElResolverClass = findClass("javax.el.BeanELResolver");
if(beanElResolverClass != null) {
boolean cleared = false;
try {
@SuppressWarnings("unchecked")
final Method purgeBeanClasses = beanElResolverClass.getDeclaredMethod("purgeBeanClasses", ClassLoader.class);
purgeBeanClasses.setAccessible(true);
purgeBeanClasses.invoke(beanElResolverClass.newInstance(), getWebApplicationClassLoader());
cleared = true;
}
catch (NoSuchMethodException e) {
// Version of javax.el probably > 2.2; no real need to clear
}
catch (Exception e) {
error(e);
}
if(! cleared) {
// Fallback, if purgeBeanClasses() could not be called
final Field propertiesField = findField(beanElResolverClass, "properties");
if(propertiesField != null) {
try {
final Map properties = (Map) propertiesField.get(null);
properties.clear();
}
catch (Exception e) {
error(e);
}
}
}
}
}
public void fixBeanValidationApiLeak() {
Class offendingClass = findClass("javax.validation.Validation$DefaultValidationProviderResolver");
if(offendingClass != null) { // Class is present on class path
Field offendingField = findField(offendingClass, "providersPerClassloader");
if(offendingField != null) {
final Object providersPerClassloader = getStaticFieldValue(offendingField);
if(providersPerClassloader instanceof Map) { // Map<ClassLoader, List<ValidationProvider<?>>> in offending code
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (providersPerClassloader) {
// Fix the leak!
((Map)providersPerClassloader).remove(getWebApplicationClassLoader());
}
}
}
}
}
/**
* Workaround for leak caused by Mojarra JSF implementation if included in the container.
* See <a href="http://java.net/jira/browse/JAVASERVERFACES-2746">JAVASERVERFACES-2746</a>
*/
protected void fixJsfLeak() {
/*
Note that since a WeakHashMap is used, it is not the map key that is the problem. However the value is a
Map with java.beans.PropertyDescriptor as value, and java.beans.PropertyDescriptor has a Hashtable in which
a class is put with "type" as key. This class may have been loaded by the web application.
One example case is the class org.primefaces.component.menubutton.MenuButton that points to a Map with a key
"model" whose PropertyDescriptor.table has key "type" with the class org.primefaces.model.MenuModel as its value.
For performance reasons however, we'll only look at the top level key and remove any that has been loaded by the
web application.
*/
Object o = getStaticFieldValue("javax.faces.component.UIComponentBase", "descriptors");
if(o instanceof WeakHashMap) {
WeakHashMap descriptors = (WeakHashMap) o;
final Set<Class> toRemove = new HashSet<Class>();
for(Object key : descriptors.keySet()) {
if(key instanceof Class && isLoadedByWebApplication((Class)key)) {
// For performance reasons, remove all classes loaded in web application
toRemove.add((Class) key);
// This would be more correct, but presumably slower
/*
Map<String, PropertyDescriptor> m = (Map<String, PropertyDescriptor>) descriptors.get(key);
for(Map.Entry<String,PropertyDescriptor> entry : m.entrySet()) {
Object type = entry.getValue().getValue("type"); // Key constant javax.el.ELResolver.TYPE
if(type instanceof Class && isLoadedByWebApplication((Class)type)) {
toRemove.add((Class) key);
}
}
*/
}
}
if(! toRemove.isEmpty()) {
info("Removing " + toRemove.size() + " classes from Mojarra descriptors cache");
for(Class clazz : toRemove) {
descriptors.remove(clazz);
}
}
}
}
/** Shutdown GeoTools cleaner thread as of http://jira.codehaus.org/browse/GEOT-2742 */
@SuppressWarnings("unchecked")
protected void fixGeoToolsLeak() {
final Class weakCollectionCleanerClass = findClass("org.geotools.util.WeakCollectionCleaner");
if(weakCollectionCleanerClass != null) {
try {
weakCollectionCleanerClass.getMethod("exit").invoke(null);
}
catch (Exception ex) {
error(ex);
}
}
}
/** Clear IntrospectionUtils caches of Tomcat and Apache Commons Modeler */
@SuppressWarnings("unchecked")
protected void clearIntrospectionUtilsCache() {
// Tomcat
final Class tomcatIntrospectionUtils = findClass("org.apache.tomcat.util.IntrospectionUtils");
if(tomcatIntrospectionUtils != null) {
try {
tomcatIntrospectionUtils.getMethod("clear").invoke(null);
}
catch (Exception ex) {
if(! mayBeJBoss) // JBoss includes this class, but no cache and no clear() method
error(ex);
}
}
// Apache Commons Modeler
final Class modelIntrospectionUtils = findClass("org.apache.commons.modeler.util.IntrospectionUtils");
if(modelIntrospectionUtils != null && ! isWebAppClassLoaderOrChild(modelIntrospectionUtils.getClassLoader())) { // Loaded outside web app
try {
modelIntrospectionUtils.getMethod("clear").invoke(null);
}
catch (Exception ex) {
warn("org.apache.commons.modeler.util.IntrospectionUtils needs to be cleared but there was an error, " +
"consider upgrading Apache Commons Modeler");
error(ex);
}
}
}
/**
* The bug detailed at https://issues.apache.org/ooo/show_bug.cgi?id=122517 is quite tricky. This is a try to
* avoid the issues by force starting the threads and it's job queue.
*/
protected void forceStartOpenOfficeJurtCleanup() {
if(stopThreads) {
if(isLoadedByWebApplication(findClass(JURT_ASYNCHRONOUS_FINALIZER))) {
/*
The com.sun.star.lib.util.AsynchronousFinalizer class was found and loaded, which means that in case the
static block that starts the daemon thread had not been started yet, it has been started now.
Now let's force Garbage Collection, with the hopes of having the finalize()ers that put Jobs on the
AsynchronousFinalizer queue be executed. Then just leave it, and handle the rest in {@link #stopThreads}.
*/
info("OpenOffice JURT AsynchronousFinalizer thread started - forcing garbage collection to invoke finalizers");
gc();
}
}
else {
// Check for class existence without loading class and thus executing static block
if(getWebApplicationClassLoader().getResource("com/sun/star/lib/util/AsynchronousFinalizer.class") != null) {
warn("OpenOffice JURT AsynchronousFinalizer thread will not be stopped if started, as stopThreads is false");
/*
By forcing Garbage Collection, we'll hopefully start the thread now, in case it would have been started by
GC later, so that at least it will appear in the logs.
*/
gc();
}
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Utility methods
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
protected ClassLoader getWebApplicationClassLoader() {
//return ClassLoaderLeakPreventor.class.getClassLoader();
// Alternative
return Thread.currentThread().getContextClassLoader();
}
/** Test if provided object is loaded with web application classloader */
protected boolean isLoadedInWebApplication(Object o) {
return (o instanceof Class) && isLoadedByWebApplication((Class)o) || // Object is a java.lang.Class instance
o != null && isLoadedByWebApplication(o.getClass());
}
/** Test if provided class is loaded with web application classloader */
protected boolean isLoadedByWebApplication(Class clazz) {
return clazz != null && isWebAppClassLoaderOrChild(clazz.getClassLoader());
}
/** Test if provided ClassLoader is the classloader of the web application, or a child thereof */
protected boolean isWebAppClassLoaderOrChild(ClassLoader cl) {
final ClassLoader webAppCL = getWebApplicationClassLoader();
// final ClassLoader webAppCL = Thread.currentThread().getContextClassLoader();
while(cl != null) {
if(cl == webAppCL)
return true;
cl = cl.getParent();
}
return false;
}
protected boolean isThreadInWebApplication(Thread thread) {
return isLoadedInWebApplication(thread) || // Custom Thread class in web app
isWebAppClassLoaderOrChild(thread.getContextClassLoader()); // Running in web application
}
@SuppressWarnings("unchecked")
protected <E> E getStaticFieldValue(Class clazz, String fieldName) {
Field staticField = findField(clazz, fieldName);
return (staticField != null) ? (E) getStaticFieldValue(staticField) : null;
}
@SuppressWarnings("unchecked")
protected <E> E getStaticFieldValue(String className, String fieldName) {
return (E) getStaticFieldValue(className, fieldName, false);
}
@SuppressWarnings("unchecked")
protected <E> E getStaticFieldValue(String className, String fieldName, boolean trySystemCL) {
Field staticField = findFieldOfClass(className, fieldName, trySystemCL);
return (staticField != null) ? (E) getStaticFieldValue(staticField) : null;
}
protected Field findFieldOfClass(String className, String fieldName) {
return findFieldOfClass(className, fieldName, false);
}
protected Field findFieldOfClass(String className, String fieldName, boolean trySystemCL) {
Class clazz = findClass(className, trySystemCL);
if(clazz != null) {
return findField(clazz, fieldName);
}
else
return null;
}
protected Class findClass(String className) {
return findClass(className, false);
}
protected Class findClass(String className, boolean trySystemCL) {
try {
return Class.forName(className);
}
// catch (NoClassDefFoundError e) {
// // Silently ignore
// return null;
// }
catch (ClassNotFoundException e) {
if (trySystemCL) {
try {
return Class.forName(className, true, ClassLoader.getSystemClassLoader());
} catch (ClassNotFoundException e1) {
// Silently ignore
return null;
}
}
// Silently ignore
return null;
}
catch (Exception ex) { // Example SecurityException
warn(ex);
return null;
}
}
protected Field findField(Class clazz, String fieldName) {
if(clazz == null)
return null;
try {
final Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true); // (Field is probably private)
return field;
}
catch (NoSuchFieldException ex) {
// Silently ignore
return null;
}
catch (Exception ex) { // Example SecurityException
warn(ex);
return null;
}
}
@SuppressWarnings("unchecked")
protected <T> T getStaticFieldValue(Field field) {
try {
return (T) field.get(null);
}
catch (Exception ex) {
warn(ex);
// Silently ignore
return null;
}
}
protected <T> T getFieldValue(Object obj, String fieldName) {
final Field field = findField(obj.getClass(), fieldName);
@SuppressWarnings("unchecked")
T fieldValue = (T) getFieldValue(field, obj);
return fieldValue;
}
protected <T> T getFieldValue(Field field, Object obj) {
try {
@SuppressWarnings("unchecked")
T fieldValue = (T) field.get(obj);
return fieldValue;
}
catch (Exception ex) {
warn(ex);
// Silently ignore
return null;
}
}
/** Is the JVM currently shutting down? */
protected boolean isJvmShuttingDown() {
try {
final Thread dummy = new Thread(); // Will never be started
Runtime.getRuntime().removeShutdownHook(dummy);
return false;
}
catch (IllegalStateException isex) {
return true; // Shutting down
}
catch (Throwable t) { // Any other Exception, assume we are not shutting down
return false;
}
}
/** Get a Collection with all Threads.
* This method is heavily inspired by org.apache.catalina.loader.WebappClassLoader.getThreads() */
protected Collection<Thread> getAllThreads() {
// This is some orders of magnitude slower...
// return Thread.getAllStackTraces().keySet();
// Find root ThreadGroup
ThreadGroup tg = Thread.currentThread().getThreadGroup();
while(tg.getParent() != null)
tg = tg.getParent();
// Note that ThreadGroup.enumerate() silently ignores all threads that does not fit into array
int guessThreadCount = tg.activeCount() + 50;
Thread[] threads = new Thread[guessThreadCount];
int actualThreadCount = tg.enumerate(threads);
while(actualThreadCount == guessThreadCount) { // Map was filled, there may be more
guessThreadCount *= 2;
threads = new Thread[guessThreadCount];
actualThreadCount = tg.enumerate(threads);
}
// Filter out nulls
final List<Thread> output = new ArrayList<Thread>();
for(Thread t : threads) {
if(t != null) {
output.add(t);
}
}
return output;
}
/**
* Loop ThreadLocals and inheritable ThreadLocals in current Thread
* and for each found, invoke the callback interface
*/
protected void forEachThreadLocalInCurrentThread(ThreadLocalProcessor threadLocalProcessor) {
final Thread thread = Thread.currentThread();
forEachThreadLocalInThread(thread, threadLocalProcessor);
}
protected void forEachThreadLocalInThread(Thread thread, ThreadLocalProcessor threadLocalProcessor) {
try {
if(java_lang_Thread_threadLocals != null) {
processThreadLocalMap(thread, threadLocalProcessor, java_lang_Thread_threadLocals.get(thread));
}
if(java_lang_Thread_inheritableThreadLocals != null) {
processThreadLocalMap(thread, threadLocalProcessor, java_lang_Thread_inheritableThreadLocals.get(thread));
}
}
catch (/*IllegalAccess*/Exception ex) {
error(ex);
}
}
protected void processThreadLocalMap(Thread thread, ThreadLocalProcessor threadLocalProcessor, Object threadLocalMap) throws IllegalAccessException {
if(threadLocalMap != null && java_lang_ThreadLocal$ThreadLocalMap_table != null) {
final Object[] threadLocalMapTable = (Object[]) java_lang_ThreadLocal$ThreadLocalMap_table.get(threadLocalMap); // java.lang.ThreadLocal.ThreadLocalMap.Entry[]
for(Object entry : threadLocalMapTable) {
if(entry != null) {
// Key is kept in WeakReference
Reference reference = (Reference) entry;
final ThreadLocal<?> threadLocal = (ThreadLocal<?>) reference.get();
if(java_lang_ThreadLocal$ThreadLocalMap$Entry_value == null) {
java_lang_ThreadLocal$ThreadLocalMap$Entry_value = findField(entry.getClass(), "value");
}
final Object value = java_lang_ThreadLocal$ThreadLocalMap$Entry_value.get(entry);
threadLocalProcessor.process(thread, reference, threadLocal, value);
}
}
}
}
protected interface ThreadLocalProcessor {
void process(Thread thread, Reference entry, ThreadLocal<?> threadLocal, Object value);
}
/** ThreadLocalProcessor that detects and warns about potential leaks */
protected class WarningThreadLocalProcessor implements ThreadLocalProcessor {
public final void process(Thread thread, Reference entry, ThreadLocal<?> threadLocal, Object value) {
final boolean customThreadLocal = isLoadedInWebApplication(threadLocal); // This is not an actual problem
final boolean valueLoadedInWebApp = isLoadedInWebApplication(value);
if(customThreadLocal || valueLoadedInWebApp ||
(value instanceof ClassLoader && isWebAppClassLoaderOrChild((ClassLoader) value))) { // The value is classloader (child) itself
// This ThreadLocal is either itself loaded by the web app classloader, or it's value is
// Let's do something about it
StringBuilder message = new StringBuilder();
if(threadLocal != null) {
if(customThreadLocal) {
message.append("Custom ");
}
message.append("ThreadLocal of type ").append(threadLocal.getClass().getName()).append(": ").append(threadLocal);
}
else {
message.append("Unknown ThreadLocal");
}
message.append(" with value ").append(value);
if(value != null) {
message.append(" of type ").append(value.getClass().getName());
if(valueLoadedInWebApp)
message.append(" that is loaded by web app");
}
warn(message.toString());
processFurther(thread, entry, threadLocal, value); // Allow subclasses to perform further processing
}
}
/**
* After having detected potential ThreadLocal leak and warned about it, this method is called.
* Subclasses may override this method to perform further processing, such as clean up.
* @param thread
* @param entry
* @param threadLocal
* @param value
*/
protected void processFurther(Thread thread, Reference entry, ThreadLocal<?> threadLocal, Object value) {
// To be overridden in subclass
}
}
/** ThreadLocalProcessor that not only detects and warns about potential leaks, but also tries to clear them */
protected class ClearingThreadLocalProcessor extends WarningThreadLocalProcessor {
public void processFurther(Thread thread, Reference entry, ThreadLocal<?> threadLocal, Object value) {
if(threadLocal != null && thread == Thread.currentThread()) { // If running for current thread and we have the ThreadLocal ...
// ... remove properly
info(" Will be remove()d");
threadLocal.remove();
}
else { // We cannot remove entry properly, so just make it stale
info(" Will be made stale for later expunging");
entry.clear(); // Clear the key
if(java_lang_ThreadLocal$ThreadLocalMap$Entry_value == null) {
java_lang_ThreadLocal$ThreadLocalMap$Entry_value = findField(entry.getClass(), "value");
}
try {
java_lang_ThreadLocal$ThreadLocalMap$Entry_value.set(entry, null); // Clear value to avoid circular references
}
catch (IllegalAccessException iaex) {
error(iaex);
}
}
}
}
/** Parse init parameter for integer value, returning default if not found or invalid */
protected static int getIntInitParameter(ServletContext servletContext, String parameterName, int defaultValue) {
final String parameterString = servletContext.getInitParameter(parameterName);
if(parameterString != null && parameterString.trim().length() > 0) {
try {
return Integer.parseInt(parameterString);
}
catch (NumberFormatException e) {
// Do nothing, return default value
}
}
return defaultValue;
}
/**
* Unlike <code>{@link System#gc()}</code> this method guarantees that garbage collection has been performed before
* returning.
*/
protected static void gc() {
Object obj = new Object();
WeakReference ref = new WeakReference<Object>(obj);
//noinspection UnusedAssignment
obj = null;
while(ref.get() != null) {
System.gc();
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Log methods
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
* Since logging frameworks are part of the problem, we don't want to depend on any of them here.
* Feel free however to subclass or fork and use a log framework, in case you think you know what you're doing.
*/
protected String getLogPrefix() {
return ClassLoaderLeakPreventor.class.getSimpleName() + ": ";
}
protected void debug(String s) {
System.out.println(getLogPrefix() + s);
}
protected void info(String s) {
System.out.println(getLogPrefix() + s);
}
protected void warn(String s) {
System.err.println(getLogPrefix() + s);
}
protected void warn(Throwable t) {
t.printStackTrace(System.err);
}
protected void error(String s) {
System.err.println(getLogPrefix() + s);
}
protected void error(Throwable t) {
t.printStackTrace(System.err);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Inner class with the sole task of killing JURT finalizer thread after it is done processing jobs.
* We need to postpone the stopping of this thread, since more Jobs may in theory be add()ed when this web application
* instance is closing down and being garbage collected.
* See https://issues.apache.org/ooo/show_bug.cgi?id=122517
*/
protected class JURTKiller extends Thread {
private final Thread jurtThread;
private final List jurtQueue;
public JURTKiller(Thread jurtThread) {
super("JURTKiller");
this.jurtThread = jurtThread;
jurtQueue = getStaticFieldValue(JURT_ASYNCHRONOUS_FINALIZER, "queue");
}
@Override
public void run() {
if(jurtQueue == null || jurtThread == null) {
error(getName() + ": No queue or thread!?");
return;
}
if(! jurtThread.isAlive()) {
warn(getName() + ": " + jurtThread.getName() + " is already dead?");
}
boolean queueIsEmpty = false;
while(! queueIsEmpty) {
try {
debug(getName() + " goes to sleep for " + THREAD_WAIT_MS_DEFAULT + " ms");
Thread.sleep(THREAD_WAIT_MS_DEFAULT);
}
catch (InterruptedException e) {
// Do nothing
}
if(State.RUNNABLE != jurtThread.getState()) { // Unless thread is currently executing a Job
debug(getName() + " about to force Garbage Collection");
gc(); // Force garbage collection, which may put new items on queue
synchronized (jurtQueue) {
queueIsEmpty = jurtQueue.isEmpty();
debug(getName() + ": JURT queue is empty? " + queueIsEmpty);
}
}
else
debug(getName() + ": JURT thread " + jurtThread.getName() + " is executing Job");
}
info(getName() + " about to kill " + jurtThread);
if(jurtThread.isAlive())
stop( jurtThread);
}
@SuppressWarnings("deprecation")
private void stop(Thread thread) {
thread.stop();
}
}
} | 04900db4-rob | src/se/jiderhamn/classloader/leak/prevention/ClassLoaderLeakPreventor.java | Java | gpl3 | 63,814 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.images;
import java.awt.Image;
import java.awt.Toolkit;
import java.io.InputStream;
import java.net.URL;
import javax.swing.ImageIcon;
/**
* Offers direct access to the images.
*/
public class Images
{
public static InputStream getInputStream(String filename)
{
return Images.class.getResourceAsStream(filename);
}
public static Image getImage(String filename)
{
try {
URL url = Images.class.getResource(filename);
if ( url == null)
return null;
return Toolkit.getDefaultToolkit().createImage( url);
} catch (Exception ex) {
return null;
}
}
public static ImageIcon getIcon(String filename)
{
return new ImageIcon(getImage( filename));
}
}
| 04900db4-rob | src/org/rapla/gui/images/Images.java | Java | gpl3 | 1,685 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui;
import org.rapla.framework.RaplaException;
import org.rapla.gui.toolkit.MenuInterface;
public interface MenuFactory
{
public MenuInterface addObjectMenu(MenuInterface menu, MenuContext context, String afterId) throws RaplaException;
public void addReservationWizards(MenuInterface menu, MenuContext context,String afterId) throws RaplaException;
}
| 04900db4-rob | src/org/rapla/gui/MenuFactory.java | Java | gpl3 | 1,326 |
package org.rapla.gui;
import org.rapla.framework.PluginDescriptor;
public interface PluginOptionPanel extends OptionPanel {
Class<? extends PluginDescriptor<?>> getPluginClass();
}
| 04900db4-rob | src/org/rapla/gui/PluginOptionPanel.java | Java | gpl3 | 185 |
package org.rapla.gui;
import org.rapla.components.util.TimeInterval;
public interface VisibleTimeInterval {
TimeInterval getVisibleTimeInterval();
}
| 04900db4-rob | src/org/rapla/gui/VisibleTimeInterval.java | Java | gpl3 | 160 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal;
import java.awt.Component;
import java.awt.FlowLayout;
import java.util.Calendar;
import java.util.Locale;
import javax.swing.BoxLayout;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import org.rapla.components.calendar.DateChangeEvent;
import org.rapla.components.calendar.DateChangeListener;
import org.rapla.components.calendar.RaplaNumber;
import org.rapla.components.calendar.RaplaTime;
import org.rapla.components.calendarview.WeekdayMapper;
import org.rapla.components.layout.TableLayout;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.configuration.RaplaConfiguration;
import org.rapla.facade.CalendarOptions;
import org.rapla.facade.internal.CalendarOptionsImpl;
import org.rapla.framework.DefaultConfiguration;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.OptionPanel;
import org.rapla.gui.RaplaGUIComponent;
public class CalendarOption extends RaplaGUIComponent implements OptionPanel, DateChangeListener
{
JPanel panel = new JPanel();
JCheckBox showExceptionsField = new JCheckBox();
@SuppressWarnings("unchecked")
JComboBox colorBlocks = new JComboBox( new String[] {
CalendarOptionsImpl.COLOR_NONE
,CalendarOptionsImpl.COLOR_RESOURCES
, CalendarOptionsImpl.COLOR_EVENTS
, CalendarOptionsImpl.COLOR_EVENTS_AND_RESOURCES
}
);
RaplaNumber rowsPerHourField = new RaplaNumber(new Double(1),new Double(1),new Double(12), false);
Preferences preferences;
CalendarOptions options;
RaplaTime worktimeStart;
RaplaTime worktimeEnd;
JPanel excludeDaysPanel = new JPanel();
JCheckBox[] box = new JCheckBox[7];
WeekdayMapper mapper;
RaplaNumber nTimesField = new RaplaNumber(new Double(1),new Double(1),new Double(365), false);
@SuppressWarnings({ "unchecked" })
JComboBox nonFilteredEvents = new JComboBox( new String[]
{
CalendarOptionsImpl.NON_FILTERED_EVENTS_TRANSPARENT,
CalendarOptionsImpl.NON_FILTERED_EVENTS_HIDDEN
}
);
JLabel worktimeEndError;
@SuppressWarnings({ "unchecked" })
JComboBox minBlockWidth = new JComboBox( new Integer[] {0,50,100,200});
JComboBox firstDayOfWeek;
RaplaNumber daysInWeekview;
public CalendarOption(RaplaContext sm) {
super( sm);
daysInWeekview = new RaplaNumber(7, 3, 35, false);
mapper = new WeekdayMapper(getLocale());
worktimeStart = createRaplaTime();
worktimeStart.setRowsPerHour( 1 );
worktimeEnd = createRaplaTime();
worktimeEnd.setRowsPerHour( 1 );
double pre = TableLayout.PREFERRED;
double fill = TableLayout.FILL;
// rows = 8 columns = 4
panel.setLayout( new TableLayout(new double[][] {{pre, 5, pre, 5 , pre, 5, pre}, {pre,5,pre,5,pre,5,pre,5,pre,5,pre,5,pre,5,pre,5,pre,5,pre,5,pre,5,pre,5,pre,5,fill}}));
panel.add( new JLabel(getString("rows_per_hour")),"0,0" );
panel.add( rowsPerHourField,"2,0");
panel.add( new JLabel(getString("start_time")),"0,2" );
JPanel worktimeStartPanel = new JPanel();
worktimeStartPanel.add( worktimeStart);
panel.add( worktimeStartPanel, "2,2,l");
panel.add( new JLabel(getString("end_time")),"0,4" );
worktimeStart.addDateChangeListener(this);
JPanel worktimeEndPanel = new JPanel();
panel.add( worktimeEndPanel,"2,4,l");
worktimeEndPanel.add( worktimeEnd);
worktimeEndError = new JLabel(getString("appointment.next_day"));
worktimeEndPanel.add( worktimeEndError);
worktimeEnd.addDateChangeListener(this);
panel.add( new JLabel(getString("color")),"0,6" );
panel.add( colorBlocks,"2,6");
showExceptionsField.setText("");
panel.add( new JLabel(getString("display_exceptions")),"0,8");
panel.add( showExceptionsField,"2,8");
panel.add( new JLabel(getString("events_not_matched_by_filter")),"0,10");
panel.add( nonFilteredEvents,"2,10");
setRenderer();
@SuppressWarnings("unchecked")
JComboBox jComboBox = new JComboBox(mapper.getNames());
firstDayOfWeek = jComboBox;
panel.add( new JLabel(getString("day1week")),"0,12");
panel.add( firstDayOfWeek,"2,12");
panel.add( new JLabel(getString("daysInWeekview")),"0,14");
panel.add( daysInWeekview,"2,14");
panel.add( new JLabel(getString("minimumBlockWidth")),"0,16");
JPanel minWidthContainer = new JPanel();
minWidthContainer.setLayout( new FlowLayout(FlowLayout.LEFT));
minWidthContainer.add(minBlockWidth);
minWidthContainer.add(new JLabel("%"));
panel.add( minWidthContainer,"2,16");
panel.add( new JLabel(getString("exclude_days")),"0,22,l,t");
panel.add( excludeDaysPanel,"2,22");
excludeDaysPanel.setLayout( new BoxLayout( excludeDaysPanel,BoxLayout.Y_AXIS));
for ( int i=0;i<box.length;i++) {
int weekday = mapper.dayForIndex( i);
box[i] = new JCheckBox(mapper.getName(weekday));
excludeDaysPanel.add( box[i]);
}
}
@SuppressWarnings("unchecked")
private void setRenderer() {
ListRenderer listRenderer = new ListRenderer();
nonFilteredEvents.setRenderer( listRenderer );
colorBlocks.setRenderer( listRenderer );
}
public JComponent getComponent() {
return panel;
}
public String getName(Locale locale) {
return getString("calendar");
}
public void setPreferences( Preferences preferences) {
this.preferences = preferences;
}
public void show() throws RaplaException {
// get the options
RaplaConfiguration config = preferences.getEntry( CalendarOptionsImpl.CALENDAR_OPTIONS);
if ( config != null) {
options = new CalendarOptionsImpl( config );
} else {
options = getCalendarOptions();
}
if ( options.isEventColoring() && options.isResourceColoring())
{
colorBlocks.setSelectedItem( CalendarOptionsImpl.COLOR_EVENTS_AND_RESOURCES);
}
else if ( options.isEventColoring() )
{
colorBlocks.setSelectedItem( CalendarOptionsImpl.COLOR_EVENTS);
}
else if ( options.isResourceColoring())
{
colorBlocks.setSelectedItem( CalendarOptionsImpl.COLOR_RESOURCES);
}
else
{
colorBlocks.setSelectedItem( CalendarOptionsImpl.COLOR_NONE);
}
showExceptionsField.setSelected( options.isExceptionsVisible());
rowsPerHourField.setNumber( new Long(options.getRowsPerHour()));
Calendar calendar = getRaplaLocale().createCalendar();
int workTime = options.getWorktimeStartMinutes();
calendar.set( Calendar.HOUR_OF_DAY, workTime / 60);
calendar.set( Calendar.MINUTE, workTime % 60);
worktimeStart.setTime( calendar.getTime() );
workTime = options.getWorktimeEndMinutes();
calendar.set( Calendar.HOUR_OF_DAY, workTime / 60);
calendar.set( Calendar.MINUTE, workTime % 60);
worktimeEnd.setTime( calendar.getTime() );
for ( int i=0;i<box.length;i++) {
int weekday = mapper.dayForIndex( i);
box[i].setSelected( options.getExcludeDays().contains( new Integer( weekday)));
}
int firstDayOfWeek2 = options.getFirstDayOfWeek();
firstDayOfWeek.setSelectedIndex( mapper.indexForDay( firstDayOfWeek2));
daysInWeekview.setNumber( options.getDaysInWeekview());
minBlockWidth.setSelectedItem( new Integer(options.getMinBlockWidth()));
nonFilteredEvents.setSelectedItem( options.isNonFilteredEventsVisible() ? CalendarOptionsImpl.NON_FILTERED_EVENTS_TRANSPARENT : CalendarOptionsImpl.NON_FILTERED_EVENTS_HIDDEN);
}
public void commit() {
// Save the options
RaplaConfiguration calendarOptions = new RaplaConfiguration("calendar-options");
DefaultConfiguration worktime = new DefaultConfiguration(CalendarOptionsImpl.WORKTIME);
DefaultConfiguration excludeDays = new DefaultConfiguration(CalendarOptionsImpl.EXCLUDE_DAYS);
DefaultConfiguration rowsPerHour = new DefaultConfiguration(CalendarOptionsImpl.ROWS_PER_HOUR);
DefaultConfiguration exceptionsVisible = new DefaultConfiguration(CalendarOptionsImpl.EXCEPTIONS_VISIBLE);
DefaultConfiguration daysInWeekview = new DefaultConfiguration(CalendarOptionsImpl.DAYS_IN_WEEKVIEW);
DefaultConfiguration firstDayOfWeek = new DefaultConfiguration(CalendarOptionsImpl.FIRST_DAY_OF_WEEK);
DefaultConfiguration minBlockWidth = new DefaultConfiguration(CalendarOptionsImpl.MIN_BLOCK_WIDTH);
daysInWeekview.setValue( this.daysInWeekview.getNumber().intValue());
int selectedIndex = this.firstDayOfWeek.getSelectedIndex();
int weekday = mapper.dayForIndex(selectedIndex);
firstDayOfWeek.setValue( weekday);
DefaultConfiguration colorBlocks = new DefaultConfiguration(CalendarOptionsImpl.COLOR_BLOCKS);
String colorValue = (String) this.colorBlocks.getSelectedItem();
if ( colorValue != null )
{
colorBlocks.setValue( colorValue );
}
calendarOptions.addChild( colorBlocks );
Calendar calendar = getRaplaLocale().createCalendar();
calendar.setTime( worktimeStart.getTime());
int worktimeStartHour = calendar.get(Calendar.HOUR_OF_DAY) ;
int worktimeStartMinute = calendar.get(Calendar.MINUTE);
calendar.setTime( worktimeEnd.getTime());
int worktimeEndHour = calendar.get(Calendar.HOUR_OF_DAY) ;
int worktimeEndMinute = calendar.get(Calendar.MINUTE);
if ( worktimeStartMinute > 0 || worktimeEndMinute > 0)
{
worktime.setValue( worktimeStartHour + ":" + worktimeStartMinute + "-" + worktimeEndHour + ":" + worktimeEndMinute );
}
else
{
worktime.setValue( worktimeStartHour + "-" + worktimeEndHour );
}
calendarOptions.addChild( worktime);
exceptionsVisible.setValue( showExceptionsField.isSelected() );
calendarOptions.addChild( exceptionsVisible);
rowsPerHour.setValue( rowsPerHourField.getNumber().intValue());
StringBuffer days = new StringBuffer();
for ( int i=0;i<box.length;i++) {
if (box[i].isSelected()) {
if ( days.length() > 0)
days.append(",");
days.append( mapper.dayForIndex( i ));
}
}
calendarOptions.addChild( rowsPerHour);
excludeDays.setValue( days.toString());
calendarOptions.addChild( excludeDays);
calendarOptions.addChild(daysInWeekview);
calendarOptions.addChild(firstDayOfWeek);
Object selectedItem = this.minBlockWidth.getSelectedItem();
if ( selectedItem != null)
{
minBlockWidth.setValue( (Integer) selectedItem);
calendarOptions.addChild(minBlockWidth);
}
DefaultConfiguration nonFilteredEventsConfig = new DefaultConfiguration(CalendarOptionsImpl.NON_FILTERED_EVENTS);
nonFilteredEventsConfig.setValue( nonFilteredEvents.getSelectedItem().toString());
calendarOptions.addChild( nonFilteredEventsConfig);
preferences.putEntry( CalendarOptionsImpl.CALENDAR_OPTIONS, calendarOptions);
}
public void dateChanged(DateChangeEvent evt) {
Calendar calendar = getRaplaLocale().createCalendar();
calendar.setTime( worktimeStart.getTime());
int worktimeS = calendar.get(Calendar.HOUR_OF_DAY)*60 + calendar.get(Calendar.MINUTE);
calendar.setTime( worktimeEnd.getTime());
int worktimeE = calendar.get(Calendar.HOUR_OF_DAY)*60 + calendar.get(Calendar.MINUTE);
worktimeE = (worktimeE == 0)?24*60:worktimeE;
boolean overnight = worktimeS >= worktimeE|| worktimeE == 24*60;
worktimeEndError.setVisible( overnight);
}
private class ListRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = 1L;
public Component getListCellRendererComponent(
//@SuppressWarnings("rawtypes")
JList list
,Object value, int index, boolean isSelected, boolean cellHasFocus) {
if ( value != null) {
setText(getString( value.toString()));
}
return this;
}
}
} | 04900db4-rob | src/org/rapla/gui/internal/CalendarOption.java | Java | gpl3 | 13,825 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.MenuElement;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.rapla.client.ClientService;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.util.IOUtil;
import org.rapla.components.util.undo.CommandHistory;
import org.rapla.components.util.undo.CommandHistoryChangedListener;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.ModificationListener;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.framework.internal.ConfigTools;
import org.rapla.gui.EditController;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.action.RestartRaplaAction;
import org.rapla.gui.internal.action.RestartServerAction;
import org.rapla.gui.internal.action.SaveableToggleAction;
import org.rapla.gui.internal.action.user.UserAction;
import org.rapla.gui.internal.common.InternMenus;
import org.rapla.gui.internal.edit.DeleteUndo;
import org.rapla.gui.internal.edit.reservation.SortedListModel;
import org.rapla.gui.internal.print.PrintAction;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.HTMLView;
import org.rapla.gui.toolkit.IdentifiableMenuEntry;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaFrame;
import org.rapla.gui.toolkit.RaplaMenu;
import org.rapla.gui.toolkit.RaplaMenuItem;
import org.rapla.gui.toolkit.RaplaSeparator;
import org.rapla.gui.toolkit.RaplaWidget;
import org.rapla.plugin.abstractcalendar.RaplaBuilder;
public class RaplaMenuBar extends RaplaGUIComponent
{
final JMenuItem exit;
final JMenuItem redo;
final JMenuItem undo;
JMenuItem templateEdit;
public RaplaMenuBar(RaplaContext context) throws RaplaException {
super(context);
RaplaMenu systemMenu = getService( InternMenus.FILE_MENU_ROLE );
systemMenu.setText( getString("file"));
RaplaMenu editMenu = getService( InternMenus.EDIT_MENU_ROLE );
editMenu.setText( getString("edit"));
RaplaMenu exportMenu = getService( InternMenus.EXPORT_MENU_ROLE );
exportMenu.setText( getString("export"));
RaplaMenu importMenu = getService( InternMenus.IMPORT_MENU_ROLE );
importMenu.setText( getString("import"));
JMenuItem newMenu = getService( InternMenus.NEW_MENU_ROLE );
newMenu.setText( getString("new"));
JMenuItem calendarSettings = getService( InternMenus.CALENDAR_SETTINGS );
calendarSettings.setText( getString("calendar"));
RaplaMenu extraMenu = getService( InternMenus.EXTRA_MENU_ROLE);
extraMenu.setText( getString("help"));
RaplaMenu adminMenu = getService( InternMenus.ADMIN_MENU_ROLE );
adminMenu.setText( getString("admin"));
RaplaMenu viewMenu = getService( InternMenus.VIEW_MENU_ROLE );
viewMenu.setText( getString("view"));
viewMenu.add( new RaplaSeparator("view_save"));
if ( getUser().isAdmin())
{
addPluginExtensions( RaplaClientExtensionPoints.ADMIN_MENU_EXTENSION_POINT, adminMenu);
}
addPluginExtensions( RaplaClientExtensionPoints.IMPORT_MENU_EXTENSION_POINT, importMenu);
addPluginExtensions( RaplaClientExtensionPoints.EXPORT_MENU_EXTENSION_POINT, exportMenu);
addPluginExtensions( RaplaClientExtensionPoints.HELP_MENU_EXTENSION_POINT, extraMenu);
addPluginExtensions( RaplaClientExtensionPoints.VIEW_MENU_EXTENSION_POINT,viewMenu);
addPluginExtensions( RaplaClientExtensionPoints.EDIT_MENU_EXTENSION_POINT, editMenu);
systemMenu.add( newMenu);
systemMenu.add( calendarSettings);
systemMenu.add( new JSeparator());
systemMenu.add( exportMenu );
systemMenu.add( importMenu );
systemMenu.add( adminMenu);
JSeparator printSep = new JSeparator();
printSep.setName(getString("calendar"));
systemMenu.add( printSep);
JMenuItem printMenu = new JMenuItem( getString("print"));
PrintAction printAction = new PrintAction(getContext());
printMenu.setAction( printAction );
printAction.setEnabled( true );
CalendarSelectionModel model = getService(CalendarSelectionModel.class);
printAction.setModel(model);
systemMenu.add( printMenu );
systemMenu.add( new JSeparator());
if ( getService(ClientService.class).canSwitchBack() ) {
JMenuItem switchBack = new JMenuItem();
switchBack.setAction( new UserAction(getContext(),null,null).setSwitchToUser());
adminMenu.add( switchBack );
}
boolean server = getUpdateModule().isClientForServer();
if ( server && isAdmin() ) {
JMenuItem restartServer = new JMenuItem();
restartServer.setAction( new RestartServerAction(getContext()));
adminMenu.add( restartServer );
}
Listener listener = new Listener();
JMenuItem restart = new JMenuItem();
restart.setAction( new RestartRaplaAction(getContext()));
systemMenu.add( restart );
systemMenu.setMnemonic('F');
exit = new JMenuItem(getString("exit"));
exit.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_Q, ActionEvent.CTRL_MASK ) );
exit.setMnemonic('x');
exit.addActionListener( listener );
systemMenu.add( exit );
redo = new JMenuItem(getString("redo"));
undo = new JMenuItem(getString("undo"));
undo.setToolTipText(getString("undo"));
undo.setIcon(getIcon("icon.undo"));
redo.addActionListener( listener);
undo.addActionListener( listener);
redo.setToolTipText(getString("redo"));
redo.setIcon(getIcon("icon.redo"));
getModification().getCommandHistory().addCommandHistoryChangedListener(listener);
undo.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_Z, ActionEvent.CTRL_MASK ) );
redo.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_Y, ActionEvent.CTRL_MASK ) );
undo.setEnabled(false);
redo.setEnabled(false);
editMenu.insertBeforeId( undo,"EDIT_BEGIN");
editMenu.insertBeforeId( redo,"EDIT_BEGIN" );
RaplaMenuItem userOptions = new RaplaMenuItem("userOptions");
editMenu.add( userOptions );
if ( getQuery().canEditTemplats( getUser()))
{
templateEdit = new RaplaMenuItem("template");
updateTemplateText();
templateEdit.addActionListener( listener);
editMenu.add( templateEdit );
}
if ( isModifyPreferencesAllowed() ) {
userOptions.setAction( createOptionAction( getQuery().getPreferences( )));
} else {
userOptions.setVisible( false );
}
{
SaveableToggleAction action = new SaveableToggleAction( context, "show_tips",RaplaBuilder.SHOW_TOOLTIP_CONFIG_ENTRY);
RaplaMenuItem menu = action.createMenuItem();
viewMenu.insertBeforeId( menu, "view_save" );
}
{
SaveableToggleAction action = new SaveableToggleAction( context, CalendarEditor.SHOW_CONFLICTS_MENU_ENTRY,CalendarEditor.SHOW_CONFLICTS_CONFIG_ENTRY);
RaplaMenuItem menu = action.createMenuItem();
viewMenu.insertBeforeId( menu, "view_save" );
}
{
SaveableToggleAction action = new SaveableToggleAction( context, CalendarEditor.SHOW_SELECTION_MENU_ENTRY,CalendarEditor.SHOW_SELECTION_CONFIG_ENTRY);
RaplaMenuItem menu = action.createMenuItem();
viewMenu.insertBeforeId( menu, "view_save" );
}
if ( isAdmin() ) {
RaplaMenuItem adminOptions = new RaplaMenuItem("adminOptions");
adminOptions.setAction( createOptionAction( getQuery().getSystemPreferences()));
adminMenu.add( adminOptions );
}
RaplaMenuItem info = new RaplaMenuItem("info");
info.setAction( createInfoAction( ));
extraMenu.add( info );
// within the help menu we need another point for the license
RaplaMenuItem license = new RaplaMenuItem("license");
// give this menu item an action to perform on click
license.setAction(createLicenseAction());
// add the license dialog below the info entry
extraMenu.add(license);
adminMenu.setEnabled( adminMenu.getMenuComponentCount() != 0 );
exportMenu.setEnabled( exportMenu.getMenuComponentCount() != 0);
importMenu.setEnabled( importMenu.getMenuComponentCount() != 0);
getUpdateModule().addModificationListener( listener);
}
protected void updateTemplateText() {
if ( templateEdit == null)
{
return;
}
String editString = getString("edit-templates");
String exitString = getString("close-template");
templateEdit.setText(isTemplateEdit() ? exitString : editString);
}
protected boolean isTemplateEdit() {
return getModification().getTemplateName() != null;
}
class Listener implements ActionListener, CommandHistoryChangedListener, ModificationListener
{
public void historyChanged()
{
CommandHistory history = getModification().getCommandHistory();
redo.setEnabled(history.canRedo());
undo.setEnabled(history.canUndo());
redo.setText(getString("redo") + ": " + history.getRedoText());
undo.setText(getString("undo") + ": " + history.getUndoText());
}
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if ( source == exit)
{
RaplaFrame mainComponent = (RaplaFrame)getMainComponent();
mainComponent.close();
}
else if ( source == templateEdit)
{
if ( isTemplateEdit())
{
getModification().setTemplateName( null );
}
else
{
templateEdit();
}
}
else
{
CommandHistory commandHistory = getModification().getCommandHistory();
try {
if ( source == redo)
{
commandHistory.redo();
}
if ( source == undo)
{
commandHistory.undo();
}
} catch (Exception ex) {
showException(ex, getMainComponent());
}
}
}
public void dataChanged(ModificationEvent evt) throws RaplaException {
updateTemplateText();
}
}
private void addPluginExtensions(
TypedComponentRole<IdentifiableMenuEntry> extensionPoint,
RaplaMenu menu) throws RaplaContextException
{
Collection<IdentifiableMenuEntry> points = getContainer().lookupServicesFor( extensionPoint);
for (IdentifiableMenuEntry menuItem: points)
{
MenuElement menuElement = menuItem.getMenuElement();
menu.add( menuElement.getComponent());
}
}
private Action createOptionAction( final Preferences preferences) {
AbstractAction action = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent arg0) {
try {
EditController editContrl = getService(EditController.class);
editContrl.edit( preferences, getMainComponent());
} catch (RaplaException ex) {
showException( ex, getMainComponent());
}
}
};
action.putValue( Action.SMALL_ICON, getIcon("icon.options") );
action.putValue( Action.NAME, getString("options"));
return action;
}
private Action createInfoAction( ) {
final String name = getString("info");
final Icon icon = getIcon("icon.info_small");
AbstractAction action = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed( ActionEvent e )
{
try {
HTMLView infoText = new HTMLView();
infoText.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
String javaversion;
try {
javaversion = System.getProperty("java.version");
} catch (SecurityException ex) {
javaversion = "-";
getLogger().warn("Permission to system properties denied!");
}
boolean isSigned = IOUtil.isSigned();
String signed = getString( isSigned ? "yes": "no");
String mainText = getI18n().format("info.text",signed,javaversion);
StringBuffer completeText = new StringBuffer();
completeText.append( mainText);
URL librariesURL = null;
try {
Enumeration<URL> resources = ConfigTools.class.getClassLoader().getResources("META-INF/readme.txt");
if ( resources.hasMoreElements())
{
librariesURL = resources.nextElement();
}
} catch (IOException e1) {
}
if ( librariesURL != null)
{
completeText.append("<pre>\n\n\n");
BufferedReader bufferedReader = null;
try
{
bufferedReader = new BufferedReader( new InputStreamReader( librariesURL.openStream()));
while ( true)
{
String line = bufferedReader.readLine();
if ( line == null)
{
break;
}
completeText.append(line);
completeText.append("\n");
}
}
catch (IOException ex)
{
try {
if ( bufferedReader != null)
{
bufferedReader.close();
}
} catch (IOException e1) {
}
}
completeText.append("</pre>");
}
String body = completeText.toString();
infoText.setBody(body);
final JScrollPane content = new JScrollPane(infoText);
DialogUI dialog = DialogUI.create( getContext(),getMainComponent(),false, content, new String[] {getString("ok")});
dialog.setTitle( name);
dialog.setSize( 780, 580);
dialog.startNoPack();
SwingUtilities.invokeLater( new Runnable()
{
public void run() {
content.getViewport().setViewPosition( new Point(0,0));
}
});
} catch (RaplaException ex) {
showException( ex, getMainComponent());
}
}
};
action.putValue( Action.SMALL_ICON, icon );
action.putValue( Action.NAME, name);
return action;
}
/**
* the action to perform when someone clicks on the license entry in the
* help section of the menu bar
*
* this method is a modified version of the existing method createInfoAction()
*/
private Action createLicenseAction()
{
final String name = getString("licensedialog.title");
final Icon icon = getIcon("icon.info_small");
// overwrite the cass AbstractAction to design our own
AbstractAction action = new AbstractAction()
{
private static final long serialVersionUID = 1L;
// overwrite the actionPerformed method that is called on click
public void actionPerformed(ActionEvent e)
{
try
{
// we need a new instance of HTMLView to visualize the short
// version of the license text including the two links
HTMLView licenseText = new HTMLView();
// giving the gui element some borders
licenseText.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
// we look up the text was originally meant for the welcome field
// and put it into a new instance of RaplaWidget
RaplaWidget welcomeField = getService(ClientService.WELCOME_FIELD);
// the following creates the dialog that pops up, when we click
// on the license entry within the help section of the menu bar
// we call the create Method of the DialogUI class and give it all necessary things
DialogUI dialog = DialogUI.create(getContext(), getMainComponent(), true, new JScrollPane(welcomeField.getComponent()), new String[] { getString("ok") });
// setting the dialog's title
dialog.setTitle(name);
// and the size of the popup window
dialog.setSize(550, 250);
// but I honestly have no clue what this startNoPack() does
dialog.startNoPack();
}
catch (RaplaException ex)
{
showException(ex, getMainComponent());
}
}
};
action.putValue(Action.SMALL_ICON, icon);
action.putValue(Action.NAME, name);
return action;
}
private void templateEdit() {
final Component parentComponent = getMainComponent();
try {
JPanel panel = new JPanel();
final JTextField textField = new JTextField(20);
addCopyPaste( textField);
panel.setPreferredSize( new Dimension(600,300));
panel.setLayout(new TableLayout( new double[][] {{TableLayout.PREFERRED,5,TableLayout.FILL, 5,TableLayout.PREFERRED},{TableLayout.PREFERRED,5,TableLayout.FILL, TableLayout.PREFERRED}}));
panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
panel.add(new JLabel("Templatename:"), "0,0");
panel.add(textField, "2,0");
addCopyPaste( textField);
final DefaultListModel model = new DefaultListModel();
@SuppressWarnings("unchecked")
final JList list = new JList(new SortedListModel(model));
Collection<String> templateNames= getQuery().getTemplateNames();
fillModel( model, templateNames);
final RaplaButton deleteButton = new RaplaButton(RaplaButton.SMALL);
deleteButton.setIcon(getIcon("icon.delete"));
panel.add( new JScrollPane(list), "0,2,2,1");
panel.add( deleteButton, "4,2,l,t");
//int selectedIndex = selectionBox.getSelectedIndex();
Object selectedItem = null;
list.setSelectedValue( selectedItem,true);
String templateName = getModification().getTemplateName();
if ( templateName != null)
{
textField.setText( templateName);
}
list.addListSelectionListener( new ListSelectionListener() {
public void valueChanged( ListSelectionEvent e )
{
String template = (String) list.getSelectedValue();
if ( template != null)
{
textField.setText( template );
}
deleteButton.setEnabled( template != null);
}
});
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if ( source == deleteButton)
{
String template = (String) list.getSelectedValue();
if ( template != null)
{
try {
Collection<Reservation> reservations = getQuery().getTemplateReservations(template);
DeleteUndo<Reservation> cmd = new DeleteUndo<Reservation>(getContext(), reservations);
getModification().getCommandHistory().storeAndExecute( cmd);
Collection<String> templateNames= getQuery().getTemplateNames();
fillModel( model, templateNames);
} catch (Exception ex) {
showException( ex, getMainComponent());
}
}
}
}
};
deleteButton.addActionListener( actionListener);
Collection<String> options = new ArrayList<String>();
options.add( getString("apply") );
options.add(getString("cancel"));
final DialogUI dlg = DialogUI.create(
getContext(),
parentComponent,true,panel,
options.toArray(new String[] {}));
dlg.setTitle(getString("edit-templates"));
dlg.getButton(options.size() - 1).setIcon(getIcon("icon.cancel"));
final AbstractAction action = new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
String template = textField.getText();
if ( template == null)
{
template = "";
}
template = template.trim();
if ( template.length() > 0)
{
String selectedTemplate = null;
Enumeration elements = model.elements();
while ( elements.hasMoreElements())
{
String test = (String)elements.nextElement();
if ( test.equals( template))
{
selectedTemplate = test;
break;
}
}
if (selectedTemplate == null)
{
selectedTemplate = template;
}
Date start = null;
if ( selectedTemplate != null)
{
try
{
Collection<Reservation> reservations = getQuery().getTemplateReservations(selectedTemplate);
for ( Reservation r:reservations)
{
Date firstDate = r.getFirstDate();
if ( start == null || firstDate.before(start ))
{
start = firstDate;
}
}
if ( start != null)
{
getService(CalendarSelectionModel.class).setSelectedDate( start);
}
}
catch (RaplaException ex)
{
showException( ex, getMainComponent());
}
}
getModification().setTemplateName( selectedTemplate);
}
else
{
getModification().setTemplateName( null);
}
dlg.close();
}
};
list.addMouseListener( new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if ( e.getClickCount() >=2)
{
action.actionPerformed( new ActionEvent( list, ActionEvent.ACTION_PERFORMED, "save"));
}
}
});
dlg.getButton(0).setAction( action);
dlg.getButton(0).setIcon(getIcon("icon.confirm"));
dlg.start();
updateTemplateText();
} catch (RaplaException ex) {
showException( ex, parentComponent);
}
}
@SuppressWarnings("unchecked")
private void fillModel(DefaultListModel model,Collection<String> templateNames) {
model.removeAllElements();
for ( String template:templateNames)
{
model.addElement( template);
}
}
}
| 04900db4-rob | src/org/rapla/gui/internal/RaplaMenuBar.java | Java | gpl3 | 25,294 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.gui.PublishExtension;
import org.rapla.gui.PublishExtensionFactory;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.toolkit.DialogUI;
/**
*/
public class PublishDialog extends RaplaGUIComponent
{
Collection<PublishExtensionFactory> extensionFactories;
PublishExtension addressCreator= null;
public PublishDialog(RaplaContext sm) throws RaplaException
{
super(sm);
if ( !isModifyPreferencesAllowed() ) {
extensionFactories = Collections.emptyList();
}
else
{
extensionFactories = getContainer().lookupServicesFor(RaplaClientExtensionPoints.PUBLISH_EXTENSION_OPTION);
}
}
public boolean hasPublishActions()
{
return extensionFactories.size() > 0;
}
String getAddress(String filename, String generator) {
try
{
StartupEnvironment env = getService( StartupEnvironment.class );
URL codeBase = env.getDownloadURL();
String pageParameters = "page="+generator+"&user=" + getUser().getUsername();
if ( filename != null)
{
pageParameters = pageParameters + "&file=" + URLEncoder.encode( filename, "UTF-8" );
}
final String urlExtension = pageParameters;
return new URL( codeBase,"rapla?" + urlExtension).toExternalForm();
}
catch (Exception ex)
{
return "Not in webstart mode. Exportname is " + filename ;
}
}
public void export(final CalendarSelectionModel model,final Component parentComponent,final String filename) throws RaplaException
{
JPanel panel = new JPanel();
panel.setPreferredSize( new Dimension(600,300));
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
final Collection<PublishExtension> extensions = new ArrayList<PublishExtension>();
addressCreator = null;
for ( PublishExtensionFactory entry:extensionFactories)
{
PublishExtensionFactory extensionFactory = entry;
PublishExtension extension = extensionFactory.creatExtension(model, new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt)
{
updateAddress(filename, extensions);
}
});
JTextField urlField = extension.getURLField();
String generator = extension.getGenerator();
if ( urlField != null)
{
String address = getAddress(filename, generator);
urlField.setText(address);
}
if ( extension.hasAddressCreationStrategy())
{
if ( addressCreator != null)
{
getLogger().error("Only one address creator can be used. " + addressCreator.toString() + " will be ignored.");
}
addressCreator = extension;
}
extensions.add( extension);
JPanel extPanel = extension.getPanel();
if ( extPanel != null)
{
panel.add( extPanel);
}
}
updateAddress(filename, extensions);
final DialogUI dlg = DialogUI.create(
getContext(),
parentComponent,false,panel,
new String[] {
getString("save")
,getString("cancel")
});
dlg.setTitle(getString("publish"));
dlg.getButton(0).setIcon(getIcon("icon.save"));
dlg.getButton(1).setIcon(getIcon("icon.cancel"));
dlg.getButton(0).setAction( new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
dlg.close();
try
{
for (PublishExtension extension :extensions)
{
extension.mapOptionTo();
}
model.save( filename);
}
catch (RaplaException ex)
{
showException( ex, parentComponent);
}
}
});
dlg.start();
}
protected void updateAddress(final String filename,
final Collection<PublishExtension> extensions) {
for ( PublishExtension entry:extensions)
{
PublishExtension extension = entry;
JTextField urlField = extension.getURLField();
if ( urlField != null)
{
String generator = extension.getGenerator();
String address;
if ( addressCreator != null )
{
address = addressCreator.getAddress(filename, generator);
}
else
{
address = getAddress(filename, generator);
}
urlField.setText(address);
}
}
}
} | 04900db4-rob | src/org/rapla/gui/internal/PublishDialog.java | Java | gpl3 | 6,375 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import org.rapla.entities.NamedComparator;
import org.rapla.entities.domain.Allocatable;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.TreeFactory;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.RaplaTree;
public class TreeAllocatableSelection extends RaplaGUIComponent implements ChangeListener {
JPanel content= new JPanel();
RaplaTree treeSelection;
JPanel buttonPanel;
JButton deleteButton;
JButton addButton;
NotificationAction deleteAction;
NotificationAction addAction;
String addDialogTitle;
public TreeAllocatableSelection(RaplaContext sm) {
super( sm);
treeSelection = new RaplaTree();
TitledBorder border = BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(Color.white,new Color(178, 178, 178)),getString("selection_resource"));
content.setBorder(border);
buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
deleteButton = new JButton();
addButton = new JButton();
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
content.setLayout(new BorderLayout());
content.add(buttonPanel, BorderLayout.NORTH);
content.add(treeSelection, BorderLayout.CENTER);
deleteAction = new NotificationAction().setDelete();
addAction = new NotificationAction().setAdd();
deleteButton.setAction(deleteAction);
addButton.setAction(addAction);
treeSelection.addChangeListener(this);
TreeFactory treeFactory = getTreeFactory();
treeSelection.getTree().setCellRenderer(treeFactory.createRenderer());
treeSelection.getTree().setModel( treeFactory.createClassifiableModel( Allocatable.ALLOCATABLE_ARRAY));
addDialogTitle = getString( "add") ;
}
Set<Allocatable> allocatables = new TreeSet<Allocatable>(new NamedComparator<Allocatable>(getLocale()));
public JComponent getComponent() {
return content;
}
final private TreeFactory getTreeFactory() {
return getService(TreeFactory.class);
}
public void setAllocatables(Collection<Allocatable> list) {
allocatables.clear();
if ( list != null ){
allocatables.addAll(list);
}
update();
}
public Collection<Allocatable> getAllocatables() {
return allocatables;
}
private void update() {
TreeFactory treeFactory = getTreeFactory();
TreeModel model = treeFactory.createClassifiableModel(allocatables.toArray(Allocatable.ALLOCATABLE_ARRAY), false);
treeSelection.exchangeTreeModel(model);
}
public void stateChanged(ChangeEvent e) {
deleteAction.setEnabled(!deleteAction.getSelected().isEmpty());
}
public String getAddDialogTitle() {
return addDialogTitle;
}
public void setAddDialogTitle(String addDialogTitle) {
this.addDialogTitle = addDialogTitle;
}
class NotificationAction extends AbstractAction {
private static final long serialVersionUID = 1L;
int ADD = 1;
int DELETE = 2;
int type;
NotificationAction setDelete() {
putValue(NAME,getString("delete"));
putValue(SMALL_ICON,getIcon("icon.delete"));
setEnabled(false);
type = DELETE;
return this;
}
NotificationAction setAdd() {
putValue(NAME,getString("add"));
putValue(SMALL_ICON,getIcon("icon.new"));
type = ADD;
return this;
}
protected List<Allocatable> getSelected() {
return getSelectedAllocatables(treeSelection);
}
protected List<Allocatable> getSelectedAllocatables(RaplaTree tree) {
List<Allocatable> allocatables = new ArrayList<Allocatable>();
List<Object> selectedElements = tree.getSelectedElements();
for ( Object obj:selectedElements)
{
allocatables.add((Allocatable) obj);
}
return allocatables;
}
public void actionPerformed(ActionEvent evt) {
try {
if (type == DELETE) {
allocatables.removeAll( getSelected());
update();
} else if (type == ADD) {
showAddDialog();
}
} catch (Exception ex) {
showException(ex,getComponent());
}
}
private void showAddDialog() throws RaplaException {
final DialogUI dialog;
RaplaTree treeSelection = new RaplaTree();
treeSelection.setMultiSelect(true);
treeSelection.getTree().setCellRenderer(getTreeFactory().createRenderer());
treeSelection.exchangeTreeModel(getTreeFactory().createClassifiableModel(getQuery().getAllocatables(),true));
treeSelection.setMinimumSize(new java.awt.Dimension(300, 200));
treeSelection.setPreferredSize(new java.awt.Dimension(400, 260));
dialog = DialogUI.create(
getContext()
,getComponent()
,true
,treeSelection
,new String[] { getString("add"),getString("cancel")});
dialog.setTitle(addDialogTitle);
dialog.getButton(0).setEnabled(false);
final JTree tree = treeSelection.getTree();
tree.addMouseListener(new MouseAdapter() {
// End dialog when a leaf is double clicked
public void mousePressed(MouseEvent e) {
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if (selPath != null && e.getClickCount() == 2) {
final Object lastPathComponent = selPath.getLastPathComponent();
if (((TreeNode) lastPathComponent).isLeaf() ) {
dialog.getButton(0).doClick();
return;
}
}
else
if (selPath != null && e.getClickCount() == 1) {
final Object lastPathComponent = selPath.getLastPathComponent();
if (((TreeNode) lastPathComponent).isLeaf() ) {
dialog.getButton(0).setEnabled(true);
return;
}
}
tree.removeSelectionPath(selPath);
}
});
dialog.start();
if (dialog.getSelectedIndex() == 0) {
List<Allocatable> selected = getSelectedAllocatables(treeSelection);
allocatables.addAll(selected);
update();
}
}
}
}
| 04900db4-rob | src/org/rapla/gui/internal/TreeAllocatableSelection.java | Java | gpl3 | 8,550 |
package org.rapla.gui.internal;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JToolBar;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.rapla.components.layout.TableLayout;
import org.rapla.entities.Entity;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.configuration.CalendarModelConfiguration;
import org.rapla.entities.configuration.Preferences;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.internal.CalendarModelImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaAction;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.common.InternMenus;
import org.rapla.gui.internal.common.MultiCalendarView;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.RaplaMenu;
import org.rapla.plugin.autoexport.AutoExportPlugin;
import org.rapla.plugin.tableview.internal.AppointmentTableViewFactory;
import org.rapla.plugin.tableview.internal.ReservationTableViewFactory;
import org.rapla.storage.UpdateResult;
public class SavedCalendarView extends RaplaGUIComponent implements ActionListener {
JComboBox selectionBox;
private boolean listenersEnabled = true;
List<FileEntry> filenames = new ArrayList<FileEntry>();
final MultiCalendarView calendarContainer;
final CalendarSelectionModel model;
final ResourceSelection resourceSelection;
JToolBar toolbar = new JToolBar();
class SaveAction extends RaplaAction
{
public SaveAction(RaplaContext sm) {
super(sm);
final String name = getString("save") ;
putValue(NAME,name);
putValue(SHORT_DESCRIPTION,name);
putValue(SMALL_ICON,getIcon("icon.save"));
}
public void actionPerformed(ActionEvent arg0) {
save();
}
}
class PublishAction extends RaplaAction
{
PublishDialog publishDialog;
public PublishAction(RaplaContext sm) throws RaplaException {
super(sm);
final String name = getString("publish") ;
putValue(NAME,name);
putValue(SHORT_DESCRIPTION,name);
putValue(SMALL_ICON,getIcon("icon.export"));
publishDialog = new PublishDialog(getContext());
}
public void actionPerformed(ActionEvent arg0) {
try
{
CalendarSelectionModel model = getService( CalendarSelectionModel.class);
FileEntry filename = getSelectedFile();
Component parentComponent = getMainComponent();
if ( filename.isDefault)
{
publishDialog.export(model, parentComponent, null);
}
else
{
publishDialog.export(model, parentComponent, filename.name);
}
}
catch (RaplaException ex) {
showException( ex, getMainComponent());
}
}
public boolean hasPublishActions()
{
return publishDialog.hasPublishActions();
}
}
class DeleteAction extends RaplaAction
{
public DeleteAction(RaplaContext sm)
{
super(sm);
final String name = getString("delete");
putValue(NAME,name);
putValue(SHORT_DESCRIPTION,name);
putValue(SMALL_ICON,getIcon("icon.delete"));
}
public void actionPerformed(ActionEvent arg0) {
try
{
String[] objects = new String[] { getSelectedFile().name};
DialogUI dlg = getInfoFactory().createDeleteDialog( objects, getMainComponent());
dlg.start();
if (dlg.getSelectedIndex() != 0)
return;
delete();
}
catch (RaplaException ex) {
showException( ex, getMainComponent());
}
}
}
final SaveAction saveAction;
final PublishAction publishAction;
final DeleteAction deleteAction;
class FileEntry implements Comparable<FileEntry>
{
String name;
boolean isDefault;
public FileEntry(String name) {
this.name=name;
}
public String toString()
{
return name;
}
public int compareTo(FileEntry o)
{
return toString().compareTo( o.toString());
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + (isDefault ? 1231 : 1237);
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FileEntry other = (FileEntry) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (isDefault != other.isDefault)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
private SavedCalendarView getOuterType() {
return SavedCalendarView.this;
}
}
public SavedCalendarView(RaplaContext context, final MultiCalendarView calendarContainer, final ResourceSelection resourceSelection, final CalendarSelectionModel model) throws RaplaException {
super(context);
// I18nBundle i18n = getI18n();
saveAction = new SaveAction(context);
publishAction = new PublishAction(context);
deleteAction = new DeleteAction( context);
this.model = model;
this.calendarContainer = calendarContainer;
this.resourceSelection = resourceSelection;
JButton save = new JButton();
JButton publish = new JButton();
JButton delete = new JButton();
toolbar.setFloatable( false);
selectionBox = new JComboBox();
selectionBox.setToolTipText( getString("calendar"));
selectionBox.setMinimumSize( new Dimension(120,30));
selectionBox.setSize( new Dimension(150,30));
// rku: updated, the next line prevented resizing the combobox when using the divider of the splitpane
// especially, when having long filenames this is annoying
//selectionBox.setMaximumSize( new Dimension(200,30));
selectionBox.setPreferredSize( new Dimension(150,30));
save.setAction( saveAction);
publish.setAction(publishAction);
RaplaMenu settingsMenu = getService(InternMenus.CALENDAR_SETTINGS);
settingsMenu.insertAfterId(new JMenuItem(saveAction), null);
if ( publishAction.hasPublishActions())
{
settingsMenu.insertAfterId(new JMenuItem(publishAction), null);
}
settingsMenu.insertAfterId(new JMenuItem(deleteAction),null);
delete.setAction( deleteAction);
// toolbar.add(new JLabel(getString("calendar")));
// toolbar.add(new JToolBar.Separator());
toolbar.add( selectionBox);
toolbar.add(new JToolBar.Separator());
toolbar.add(save);
save.setText("");
publish.setText("");
delete.setText("");
if ( publishAction.hasPublishActions())
{
toolbar.add(publish);
}
toolbar.add(delete);
toolbar.setBorder( BorderFactory.createEmptyBorder(5, 5, 5, 5));
update();
final int defaultIndex = getDefaultIndex();
if (defaultIndex != -1)
selectionBox.setSelectedIndex(defaultIndex);
else
selectionBox.setSelectedIndex(0);
updateTooltip();
selectionBox.addActionListener( this);
}
public void actionPerformed(ActionEvent e) {
updateTooltip();
if ( !listenersEnabled)
{
return;
}
try
{
changeSelection();
}
catch (RaplaException ex) {
showException( ex, getMainComponent());
}
}
protected void updateTooltip() {
Object selectedItem = selectionBox.getSelectedItem();
if ( selectedItem != null )
{
selectionBox.setToolTipText(selectedItem.toString());
}
}
public JComponent getComponent() {
return toolbar;
}
private void changeSelection() throws RaplaException
{
FileEntry selectedFile = getSelectedFile();
// keep current date in mind
final Date tmpDate = model.getSelectedDate();
// keep in mind if current model had saved date
String tmpModelHasStoredCalenderDate = model.getOption(CalendarModel.SAVE_SELECTED_DATE);
if(tmpModelHasStoredCalenderDate == null)
tmpModelHasStoredCalenderDate = "false";
// load sets stored date
if ( selectedFile.isDefault)
{
model.load(null);
}
else
{
model.load(selectedFile.name);
}
closeFilter();
// check if new model had stored date
String newModelHasStoredCalenderDate = model.getOption(CalendarModel.SAVE_SELECTED_DATE);
if(newModelHasStoredCalenderDate == null)
newModelHasStoredCalenderDate = "false";
if ("false".equals(newModelHasStoredCalenderDate)) {
if ("false".equals(tmpModelHasStoredCalenderDate))
// if we are switching from a model with saved date to a model without date we reset to current date
{
model.setSelectedDate(tmpDate);
} else {
model.setSelectedDate(new Date());
}
}
updateActions();
Entity preferences = getQuery().getPreferences();
UpdateResult modificationEvt = new UpdateResult( getUser());
modificationEvt.addOperation( new UpdateResult.Change(preferences, preferences));
resourceSelection.dataChanged(modificationEvt);
calendarContainer.update(modificationEvt);
calendarContainer.getSelectedCalendar().scrollToStart();
}
public void closeFilter() {
// CKO Not a good solution. FilterDialogs should close themselfs when model changes.
// BJO 00000139
if(resourceSelection.getFilterButton().isOpen())
resourceSelection.getFilterButton().doClick();
if(calendarContainer.getFilterButton().isOpen())
calendarContainer.getFilterButton().doClick();
// BJO 00000139
}
public void update() throws RaplaException
{
updateActions();
try
{
listenersEnabled = false;
final FileEntry item = getSelectedFile();
DefaultComboBoxModel model = updateModel();
if ( item != null )
{
model.setSelectedItem( item );
}
}
finally
{
listenersEnabled = true;
}
}
@SuppressWarnings("unchecked")
protected DefaultComboBoxModel updateModel() throws RaplaException,
EntityNotFoundException {
final Preferences preferences = getQuery().getPreferences();
Map<String, CalendarModelConfiguration> exportMap= preferences.getEntry(AutoExportPlugin.PLUGIN_ENTRY);
filenames.clear();
if ( exportMap != null) {
for (Iterator<String> it= exportMap.keySet().iterator();it.hasNext();) {
String filename = it.next();
filenames.add( new FileEntry(filename));
}
}
// rku: sort entries by name
Collections.sort(filenames);
final FileEntry defaultEntry = new FileEntry(getString("default") );
defaultEntry.isDefault = true;
filenames.add(0,defaultEntry);
DefaultComboBoxModel model = new DefaultComboBoxModel(filenames.toArray());
selectionBox.setModel(model);
return model;
}
private void updateActions() {
FileEntry selectedFile = getSelectedFile();
boolean isDefault = selectedFile == null || selectedFile.isDefault ;
final boolean modifyPreferencesAllowed = isModifyPreferencesAllowed() && getModification().getTemplateName() == null;
saveAction.setEnabled(modifyPreferencesAllowed );
publishAction.setEnabled( modifyPreferencesAllowed);
deleteAction.setEnabled( !isDefault && modifyPreferencesAllowed);
}
public void save(final String filename) throws RaplaException
{
Preferences preferences = ((CalendarModelImpl)model).createStorablePreferences(filename);
getModification().store( preferences);
// TODO Enable undo with a specific implementation, that does not overwrite all preference changes and regards dynamic type changes
// Map<Preferences, Preferences> originalMap = getModification().getPersistant(Collections.singletonList(preferences) );
// Preferences original = originalMap.get(preferences);
// Collection<Preferences> originalList = original != null ? Collections.singletonList( original): null;
// Collection<Preferences> newList = Collections.singletonList(preferences);
// String file = (filename != null) ? filename : getString("default");
// String commandoName = getString("save")+ " " + getString("calendar") + " " + file ;
// SaveUndo<Preferences> cmd = new SaveUndo<Preferences>(getContext(), newList, originalList, commandoName);
// getModification().getCommandHistory().storeAndExecute( cmd);
}
private void delete() throws RaplaException
{
final FileEntry selectedFile = getSelectedFile();
if ( selectedFile == null || selectedFile.isDefault)
{
return;
}
final Preferences preferences = newEditablePreferences();
Map<String,CalendarModelConfiguration> exportMap= preferences.getEntry(AutoExportPlugin.PLUGIN_ENTRY);
Map<String,CalendarModelConfiguration> newMap = new TreeMap<String,CalendarModelConfiguration>();
for (Iterator<String> it= exportMap.keySet().iterator();it.hasNext();) {
String filename = it.next();
if (!filename.equals( selectedFile.name)) {
CalendarModelConfiguration entry = exportMap.get( filename );
newMap.put( filename, entry);
}
}
preferences.putEntry( AutoExportPlugin.PLUGIN_ENTRY, getModification().newRaplaMap( newMap ));
getModification().store( preferences);
// TODO Enable undo with a specific implementation, that does not overwrite all preference changes and regards dynamic type changes
// Collection<Preferences> originalList = Collections.singletonList(getQuery().getPreferences());
// Collection<Preferences> newList = Collections.singletonList(preferences);
// String commandoName = getString("delete")+ " " + getString("calendar") + " " + selectedFile.name;
// SaveUndo<Preferences> cmd = new SaveUndo<Preferences>(getContext(), newList, originalList, commandoName);
// getModification().getCommandHistory().storeAndExecute( cmd);
final int defaultIndex = getDefaultIndex();
if (defaultIndex != -1)
selectionBox.setSelectedIndex(defaultIndex);
else
selectionBox.setSelectedIndex(0);
//changeSelection();
}
private int getDefaultIndex() {
return ((DefaultComboBoxModel) selectionBox.getModel()).getIndexOf(getString("default"));
}
private void save() {
final FileEntry selectedFile = getSelectedFile();
final Component parentComponent = getMainComponent();
try {
JPanel panel = new JPanel();
final JTextField textField = new JTextField(20);
addCopyPaste( textField);
String dateString;
if( model.getViewId().equals(ReservationTableViewFactory.TABLE_VIEW)
|| model.getViewId().equals(AppointmentTableViewFactory.TABLE_VIEW))
dateString = getRaplaLocale().formatDate(model.getStartDate()) + " - " + getRaplaLocale().formatDate(model.getEndDate());
else
dateString = getRaplaLocale().formatDate(model.getSelectedDate());
final JCheckBox saveSelectedDateField = new JCheckBox(getI18n().format("including_date",dateString));
panel.setPreferredSize( new Dimension(600,300));
panel.setLayout(new TableLayout( new double[][] {{TableLayout.PREFERRED,5,TableLayout.FILL},{TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.FILL}}));
panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
panel.add(new JLabel(getString("file.enter_name") +":"), "0,0");
panel.add(textField, "2,0");
addCopyPaste( textField);
panel.add(saveSelectedDateField, "2,2");
final String entry = model.getOption(CalendarModel.SAVE_SELECTED_DATE);
if(entry != null)
saveSelectedDateField.setSelected(entry.equals("true"));
@SuppressWarnings("unchecked")
final JList list = new JList(filenames.toArray());
panel.add( new JScrollPane(list), "0,4,2,1");
//int selectedIndex = selectionBox.getSelectedIndex();
Object selectedItem = selectionBox.getSelectedItem();
if ( selectedItem != null)
{
list.setSelectedValue( selectedItem,true);
}
textField.setText( selectedFile.toString());
list.addListSelectionListener( new ListSelectionListener() {
public void valueChanged( ListSelectionEvent e )
{
FileEntry filename = (FileEntry) list.getSelectedValue();
if ( filename != null) {
textField.setText( filename.toString() );
try {
final CalendarSelectionModel m = getModification().newCalendarModel( getUser());
if (filename.isDefault )
{
m.load(null);
}
else
{
m.load(filename.toString());
}
final String entry = m.getOption(CalendarModel.SAVE_SELECTED_DATE);
if( entry != null)
saveSelectedDateField.setSelected(entry.equals("true"));
} catch (RaplaException ex) {
showException( ex, getMainComponent());
}
}
}
});
final DialogUI dlg = DialogUI.create(
getContext(),
parentComponent,true,panel,
new String[] {
getString("save")
,getString("cancel")
});
dlg.setTitle(getString("save") + " " +getString("calendar_settings"));
dlg.getButton(0).setIcon(getIcon("icon.save"));
dlg.getButton(1).setIcon(getIcon("icon.cancel"));
dlg.getButton(0).setAction( new AbstractAction() {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) {
String filename = textField.getText().trim();
if (filename.length() == 0)
{
showWarning(getString("error.no_name"), parentComponent);
return;
}
dlg.close();
try
{
String saveSelectedDate = saveSelectedDateField.isSelected() ? "true" : "false";
model.setOption( CalendarModel.SAVE_SELECTED_DATE, saveSelectedDate);
FileEntry selectedValue = (FileEntry)list.getSelectedValue();
final boolean isDefault;
if ( selectedValue != null)
{
isDefault = selectedValue.isDefault && filename.equals( selectedValue.name );
}
else
{
isDefault = filename.equals( getString("default") );
}
if ( isDefault)
{
save(null);
try
{
listenersEnabled = false;
selectionBox.setSelectedIndex(0);
}
finally
{
listenersEnabled = true;
}
}
else
{
// We reset exports for newly created files
{
FileEntry fileEntry = findInModel(filename);
if ( fileEntry == null)
{
model.resetExports();
}
}
save(filename);
try
{
listenersEnabled = false;
updateModel();
FileEntry fileEntry = findInModel(filename);
if ( fileEntry != null)
{
selectionBox.setSelectedItem( fileEntry);
}
else
{
selectionBox.setSelectedIndex(0);
}
}
finally
{
listenersEnabled = true;
}
}
}
catch (RaplaException ex)
{
showException( ex, parentComponent);
}
}
private FileEntry findInModel(String filename)
{
ComboBoxModel selection = selectionBox.getModel();
for ( int i=0;i<selection.getSize();i++)
{
final FileEntry elementAt = (FileEntry) selection.getElementAt( i);
if ( !elementAt.isDefault && elementAt.toString().equals(filename))
{
return elementAt;
}
}
return null;
}
});
dlg.start();
} catch (RaplaException ex) {
showException( ex, parentComponent);
}
}
private FileEntry getSelectedFile()
{
ComboBoxModel model2 = selectionBox.getModel();
FileEntry selectedItem = (FileEntry)model2.getSelectedItem();
return selectedItem;
}
}
| 04900db4-rob | src/org/rapla/gui/internal/SavedCalendarView.java | Java | gpl3 | 23,990 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal;
import java.util.Locale;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.rapla.RaplaMainContainer;
import org.rapla.components.calendar.RaplaNumber;
import org.rapla.components.layout.TableLayout;
import org.rapla.entities.configuration.Preferences;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.UpdateModule;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.OptionPanel;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.plugin.export2ical.ICalTimezones;
public class RaplaStartOption extends RaplaGUIComponent implements OptionPanel {
JPanel panel = new JPanel();
JTextField calendarName;
Preferences preferences;
private JComboBox cboTimezone;
ICalTimezones timezoneService;
private JCheckBox ownReservations;
RaplaNumber seconds = new RaplaNumber(new Double(10),new Double(10),null, false);
public RaplaStartOption(RaplaContext context, ICalTimezones timezoneService) throws RaplaException {
super( context );
double pre = TableLayout.PREFERRED;
panel.setLayout( new TableLayout(new double[][] {{pre, 5,pre, 5, pre}, {pre,5,pre, 5 , pre, 5, pre}}));
this.timezoneService = timezoneService;
calendarName = new JTextField();
addCopyPaste( calendarName);
calendarName.setColumns(20);
panel.add( new JLabel(getString("custom_applicationame")),"0,0" );
panel.add( calendarName,"2,0");
calendarName.setEnabled(true);
String[] timeZoneIDs = getTimeZonesFromResource();
panel.add(new JLabel(getString("timezone")), "0,2");
@SuppressWarnings("unchecked")
JComboBox jComboBox = new JComboBox(timeZoneIDs);
cboTimezone = jComboBox;
panel.add(cboTimezone, "2,2");
cboTimezone.setEditable(false);
panel.add(new JLabel( getString("defaultselection") + " '" + getString("only_own_reservations") +"'"), "0,4");
ownReservations = new JCheckBox();
panel.add(ownReservations, "2,4");
seconds.getNumberField().setBlockStepSize( 60);
seconds.getNumberField().setStepSize( 10);
panel.add( new JLabel(getString("seconds")),"4,6" );
panel.add( seconds,"2,6");
panel.add( new JLabel(getString("connection") + ": " + getI18n().format("interval.format", "","")),"0,6" );
addCopyPaste( seconds.getNumberField());
}
public JComponent getComponent() {
return panel;
}
public String getName(Locale locale) {
return getString("options");
}
public void setPreferences( Preferences preferences) {
this.preferences = preferences;
}
public void show() throws RaplaException {
String name = preferences.getEntryAsString( RaplaMainContainer.TITLE,"");
calendarName.setText(name);
try {
String timezoneId = preferences.getEntryAsString( RaplaMainContainer.TIMEZONE,timezoneService.getDefaultTimezone().get());
cboTimezone.setSelectedItem(timezoneId);
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
boolean selected= preferences.getEntryAsBoolean( CalendarModel.ONLY_MY_EVENTS_DEFAULT, true);
ownReservations.setSelected( selected);
int delay = preferences.getEntryAsInteger( UpdateModule.REFRESH_INTERVAL_ENTRY, UpdateModule.REFRESH_INTERVAL_DEFAULT);
seconds.setNumber( new Long(delay / 1000));
seconds.setEnabled(getClientFacade().isClientForServer());
}
public void commit() {
String title = calendarName.getText();
if ( title.trim().length() > 0)
{
preferences.putEntry( RaplaMainContainer.TITLE,title );
}
else
{
preferences.putEntry( RaplaMainContainer.TITLE, (String)null);
}
String timeZoneId = String.valueOf(cboTimezone.getSelectedItem());
preferences.putEntry( RaplaMainContainer.TIMEZONE, timeZoneId);
boolean selected= ownReservations.isSelected();
preferences.putEntry( CalendarModel.ONLY_MY_EVENTS_DEFAULT, selected);
int delay = seconds.getNumber().intValue() * 1000;
preferences.putEntry( UpdateModule.REFRESH_INTERVAL_ENTRY, delay );
}
/**
* Gets all the iCal4J supported TimeZones from the Resource File They are
* generated by trial-and error in the BUILD event.
*
* @return String[] of the TimeZones for direct use in the ComboBox
* @throws RaplaException
*/
private String[] getTimeZonesFromResource() throws RaplaException
{
try
{
String zoneString = timezoneService.getICalTimezones().get();
return zoneString.split(";");
}
catch (RaplaException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new RaplaException(ex);
}
}
}
| 04900db4-rob | src/org/rapla/gui/internal/RaplaStartOption.java | Java | gpl3 | 5,932 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Gereon Fassbender, Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.print;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.util.HashMap;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.components.iolayer.ComponentPrinter;
import org.rapla.components.iolayer.IOInterface;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.RaplaComponent;
import org.rapla.framework.Container;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaDefaultContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.SwingCalendarView;
import org.rapla.gui.SwingViewFactory;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.ErrorDialog;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.plugin.abstractcalendar.MultiCalendarPrint;
public class CalendarPrintDialog extends DialogUI
{
private static final long serialVersionUID = 1L;
private JPanel titlePanel = new JPanel();
private JPanel southPanel = new JPanel();
private JLabel titleLabel = new JLabel();
private JLabel sizeLabel = new JLabel();
private JComboBox endDate;
private JTextField titleEdit = new JTextField();
private RaplaButton cancelbutton;
private RaplaButton formatbutton;
private RaplaButton printbutton;
private RaplaButton savebutton;
private JScrollPane scrollPane;
IOInterface printTool;
ExportServiceList exportServiceList;
// public static int[] sizes = new int[] {50,60,70,80,90,100,120,150,180,200};
public static double defaultBorder = 11.0; //11 mm defaultBorder
I18nBundle i18n;
Listener listener = new Listener();
PageFormat m_format;
protected SwingCalendarView currentView;
CalendarSelectionModel model;
Printable printable;
int curPage = 0;
JButton previousPage = new JButton("<");
JLabel pageLabel = new JLabel();
JButton nextPage = new JButton(">");
boolean updatePageCount = true;
int pageCount;
private JComponent page = new JComponent()
{
private static final long serialVersionUID = 1L;
public void paint(Graphics g)
{
try {
if ( updatePageCount )
{
pageCount = 0;
Graphics hidden = g.create();
while ( true )
{
int status = printable.print( hidden, m_format, pageCount);
boolean isNotExistant = status == Printable.NO_SUCH_PAGE;
if ( isNotExistant)
{
break;
}
pageCount++;
}
}
if ( curPage >= pageCount)
{
curPage = pageCount-1;
}
paintPaper( g, m_format );
printable.print( g, m_format, curPage);
pageLabel.setText(""+ (curPage +1) + "/" + pageCount);
boolean isLast = curPage >= pageCount -1;
nextPage.setEnabled( !isLast);
previousPage.setEnabled( curPage > 0);
savebutton.setEnabled(pageCount!=0);
} catch (PrinterException e) {
e.printStackTrace();
}
finally
{
updatePageCount = false;
}
}
protected void paintPaper(Graphics g, PageFormat format ) {
g.setColor(Color.white);
Rectangle rect = g.getClipBounds();
int paperHeight = (int)format.getHeight();
int paperWidth = (int)format.getWidth();
g.fillRect(rect.x, rect.y , Math.min(rect.width,Math.max(0,paperWidth-rect.x)), Math.min(rect.height, Math.max(0,paperHeight- rect.y)));
g.setColor(Color.black);
g.drawRect(1, 1 , paperWidth - 2, paperHeight - 2);
}
};
public static CalendarPrintDialog create(RaplaContext sm,Component owner,boolean modal,CalendarSelectionModel model,PageFormat format) throws RaplaException {
CalendarPrintDialog dlg;
Component topLevel = getOwnerWindow(owner);
if (topLevel instanceof Dialog)
dlg = new CalendarPrintDialog(sm,(Dialog)topLevel);
else
dlg = new CalendarPrintDialog(sm,(Frame)topLevel);
try {
dlg.init(modal,model,format);
} catch (Exception ex) {
throw new RaplaException( ex );
}
return dlg;
}
protected CalendarPrintDialog(RaplaContext context,Dialog owner) throws RaplaException {
super(context,owner);
init(context);
}
protected CalendarPrintDialog(RaplaContext context,Frame owner) throws RaplaException {
super(context,owner);
init(context);
}
private void init(RaplaContext context) throws RaplaException{
exportServiceList = new ExportServiceList( context);
}
private void init(boolean modal,CalendarSelectionModel model,PageFormat format) throws Exception {
super.init(modal,new JPanel(),new String[] {"print","format","print_to_file","cancel"});
this.model = model;
Map<String,SwingViewFactory> factoryMap = new HashMap<String, SwingViewFactory>();
for (SwingViewFactory fact: getContext().lookup(Container.class).lookupServicesFor(RaplaClientExtensionPoints.CALENDAR_VIEW_EXTENSION))
{
String id = fact.getViewId();
factoryMap.put( id , fact);
}
RaplaContext context = getContext();
printTool = context.lookup(IOInterface.class);
i18n = context.lookup(RaplaComponent.RAPLA_RESOURCES);
m_format = format;
if (m_format == null) {
m_format = createPageFormat();
m_format.setOrientation(m_format.getOrientation());
}
SwingViewFactory factory = factoryMap.get( model.getViewId());
RaplaDefaultContext contextWithPrintInfo = new RaplaDefaultContext(context);
contextWithPrintInfo.put(SwingViewFactory.PRINT_CONTEXT, new Boolean(true));
currentView = factory.createSwingView( contextWithPrintInfo, model, false);
if ( currentView instanceof Printable)
{
printable = (Printable)currentView;
}
else
{
Component comp = currentView.getComponent();
printable = new ComponentPrinter( comp, comp.getPreferredSize());
}
String title = model.getTitle();
content.setLayout(new BorderLayout());
titlePanel.add(titleLabel);
titlePanel.add(titleEdit);
new RaplaGUIComponent( context).addCopyPaste(titleEdit);
if ( currentView instanceof MultiCalendarPrint)
{
MultiCalendarPrint multiPrint = (MultiCalendarPrint) currentView;
sizeLabel.setText(multiPrint.getCalendarUnit() + ":");
String[] blockSizes = new String[52];
for (int i=0;i<blockSizes.length;i++)
{
blockSizes[i] = String.valueOf(i+1);
}
@SuppressWarnings("unchecked")
JComboBox jComboBox = new JComboBox(blockSizes);
endDate= jComboBox;
endDate.setEditable(true);
endDate.setPreferredSize( new Dimension(40, 30));
titlePanel.add(Box.createHorizontalStrut(10));
titlePanel.add(sizeLabel);
titlePanel.add(endDate);
titlePanel.add(Box.createHorizontalStrut(10));
endDate.addActionListener(listener);
}
titlePanel.add(previousPage);
titlePanel.add(nextPage);
titlePanel.add(pageLabel);
titleEdit.setColumns(30);
titleEdit.setText(title);
content.add(titlePanel, BorderLayout.NORTH);
scrollPane =new JScrollPane( page );
scrollPane.setPreferredSize(new Dimension(730,450));
content.add(scrollPane, BorderLayout.CENTER);
content.add(southPanel, BorderLayout.SOUTH);
southPanel.setMaximumSize( new Dimension(1,1));
southPanel.setMinimumSize( new Dimension(1,1));
southPanel.setPreferredSize( new Dimension(1,1));
southPanel.setLayout( null);
southPanel.add( currentView.getComponent());
scrollPane.getVerticalScrollBar().setUnitIncrement(10);
scrollPane.getHorizontalScrollBar().setUnitIncrement(10);
updateSizes( m_format);
printbutton = getButton(0);
printbutton.setAction(listener);
formatbutton = getButton(1);
formatbutton.setAction(listener);
savebutton = getButton(2);
savebutton.setAction(listener);
cancelbutton = getButton(3);
savebutton.setVisible(exportServiceList.getServices().length>0);
//swingCalendar.setPrintView(true);
currentView.update();
//sizeLabel.setText("Endedatum:");
titleLabel.setText(i18n.getString("weekview.print.title_textfield")+":");
setTitle(i18n.getString("weekview.print.dialog_title"));
printbutton.setIcon(i18n.getIcon("icon.print"));
savebutton.setText(i18n.getString("print_to_file"));
savebutton.setIcon(i18n.getIcon("icon.pdf"));
printbutton.setText(i18n.getString("print"));
formatbutton.setText(i18n.getString("weekview.print.format_button"));
cancelbutton.setText(i18n.getString("cancel"));
cancelbutton.setIcon(i18n.getIcon("icon.cancel"));
pageLabel.setText(""+1);
/*
if (getSession().getValue(LAST_SELECTED_SIZE) != null)
weekview.setSlotSize(((Integer)getSession().getValue(LAST_SELECTED_SIZE)).intValue());
*/
// int columnSize = model.getSize();
// sizeChooser.setSelectedItem(String.valueOf(columnSize));
titleEdit.addActionListener(listener);
titleEdit.addKeyListener(listener);
nextPage.addActionListener( listener);
previousPage.addActionListener( listener);
}
private void updateSizes( @SuppressWarnings("unused") PageFormat format)
{
//double paperHeight = format.getHeight();
//int height = (int)paperHeight + 100;
int height = 2000;
int width = 900;
updatePageCount = true;
page.setPreferredSize( new Dimension( width,height));
}
private PageFormat createPageFormat() {
PageFormat format= (PageFormat) printTool.defaultPage().clone();
format.setOrientation(PageFormat.LANDSCAPE);
Paper paper = format.getPaper();
paper.setImageableArea(
defaultBorder * IOInterface.MM_TO_INCH * 72
,defaultBorder * IOInterface.MM_TO_INCH * 72
,paper.getWidth() - 2 * defaultBorder * IOInterface.MM_TO_INCH * 72
,paper.getHeight() - 2 * defaultBorder * IOInterface.MM_TO_INCH * 72
);
format.setPaper(paper);
return format;
}
public void start() {
super.start();
}
private class Listener extends AbstractAction implements KeyListener {
private static final long serialVersionUID = 1L;
public void keyReleased(KeyEvent evt) {
try {
processTitleChange();
} catch (Exception ex) {
showException(ex);
}
}
protected void processTitleChange() throws RaplaException {
String oldTitle = model.getTitle();
String newTitle = titleEdit.getText();
model.setTitle(newTitle);
// only update view if title is set or removed not on every keystroke
if ((( oldTitle == null || oldTitle.length() == 0) && (newTitle != null && newTitle.length() > 0))
|| ((oldTitle != null && oldTitle.length() > 0 ) && ( newTitle == null || newTitle.length() ==0))
)
{
currentView.update(); // BJO performance issue
}
scrollPane.invalidate();
scrollPane.repaint();
}
public void keyTyped(KeyEvent evt) {
}
public void keyPressed(KeyEvent evt) {
}
public void actionPerformed(ActionEvent evt) {
try {
if (evt.getSource()==endDate) {
try {
Object selectedItem = endDate.getSelectedItem();
if ( selectedItem != null )
{
try
{
Integer units = Integer.valueOf(selectedItem.toString());
((MultiCalendarPrint)currentView).setUnits( units);
}
catch (NumberFormatException ex)
{
}
}
updatePageCount = true;
} catch (Exception ex) {
return;
}
currentView.update();
scrollPane.invalidate();
scrollPane.repaint();
}
if (evt.getSource()==titleEdit) {
processTitleChange();
}
if (evt.getSource()==formatbutton) {
m_format= printTool.showFormatDialog(m_format);
scrollPane.invalidate();
scrollPane.repaint();
updateSizes( m_format);
}
if (evt.getSource()==nextPage) {
curPage++;
scrollPane.repaint();
}
if (evt.getSource()==previousPage) {
curPage = Math.max(0,curPage -1 );
scrollPane.repaint();
}
if (evt.getSource()==printbutton) {
if (printTool.print(printable, m_format, true))
{
// We can't close or otherwise it won't work under windows
//close();
}
}
if (evt.getSource()==savebutton) {
boolean success = exportServiceList.export(printable, m_format, scrollPane);
Component topLevel = getParent();
if(success )
{
if (confirmPrint(topLevel))
{
close();
}
}
}
} catch (Exception ex) {
showException(ex);
}
}
}
protected boolean confirmPrint(Component topLevel) {
try {
DialogUI dlg = DialogUI.create(
getContext()
,topLevel
,true
,i18n.getString("print")
,i18n.getString("file_saved")
,new String[] { i18n.getString("ok")}
);
dlg.setIcon(i18n.getIcon("icon.pdf"));
dlg.setDefault(0);
dlg.start();
return (dlg.getSelectedIndex() == 0);
} catch (RaplaException e) {
return true;
}
}
public void showException(Exception ex) {
ErrorDialog dialog;
try {
dialog = new ErrorDialog(getContext());
dialog.showExceptionDialog(ex,this);
} catch (RaplaException e) {
}
}
}
| 04900db4-rob | src/org/rapla/gui/internal/print/CalendarPrintDialog.java | Java | gpl3 | 16,772 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.print;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.print.PageFormat;
import javax.swing.SwingUtilities;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.RaplaAction;
public class PrintAction extends RaplaAction {
CalendarSelectionModel model;
PageFormat m_pageFormat;
public PrintAction(RaplaContext sm) {
super( sm);
setEnabled(false);
putValue(NAME,getString("print"));
putValue(SMALL_ICON,getIcon("icon.print"));
}
public void setModel(CalendarSelectionModel settings) {
this.model = settings;
setEnabled(settings != null);
}
public void setPageFormat(PageFormat pageFormat) {
m_pageFormat = pageFormat;
}
public void actionPerformed(ActionEvent evt) {
Component parent = getMainComponent();
try {
boolean modal = true;
final CalendarPrintDialog dialog = CalendarPrintDialog.create(getContext(),parent,modal, model, m_pageFormat);
final Dimension dimension = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
dialog.setSize(new Dimension(
Math.min(dimension.width,900)
,Math.min(dimension.height-10,700)
)
);
SwingUtilities.invokeLater( new Runnable() {
public void run()
{
dialog.setSize(new Dimension(
Math.min(dimension.width,900)
,Math.min(dimension.height-11,699)
)
);
}
}
);
dialog.startNoPack();
} catch (Exception ex) {
showException(ex, parent);
}
}
}
| 04900db4-rob | src/org/rapla/gui/internal/print/PrintAction.java | Java | gpl3 | 3,026 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.print;
import java.awt.Component;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.util.Locale;
import org.rapla.components.iolayer.IOInterface;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.RaplaGUIComponent;
public class PDFExportService extends RaplaGUIComponent implements ExportService {
public final static String EXPORT_DIR = PDFExportService.class.getName() + ".dir";
IOInterface printInterface;
public PDFExportService(RaplaContext sm) {
super(sm);
printInterface = getService(IOInterface.class);
}
public boolean export(Printable printable,PageFormat pageFormat,Component parentComponent) throws Exception
{
String dir = (String) getSessionMap().get(EXPORT_DIR);
boolean isPDF = true;
String file = printInterface.saveAsFileShowDialog
(
dir
,printable
,pageFormat
,false
,parentComponent
, isPDF
);
if (file != null)
{
getSessionMap().put(EXPORT_DIR,file);
return true;
}
return false;
}
public String getName(Locale locale) {
return "PDF";
}
}
| 04900db4-rob | src/org/rapla/gui/internal/print/PDFExportService.java | Java | gpl3 | 2,292 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.print;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.util.Collection;
import java.util.HashMap;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListSelectionModel;
import org.rapla.components.iolayer.IOInterface;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaContextException;
import org.rapla.framework.RaplaException;
import org.rapla.framework.StartupEnvironment;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.common.NamedListCellRenderer;
import org.rapla.gui.toolkit.DialogUI;
public class ExportServiceList extends RaplaGUIComponent {
HashMap<Object,ExportService> exporters = new HashMap<Object,ExportService>();
/**
* @param sm
* @throws RaplaException
*/
public ExportServiceList(RaplaContext sm) throws RaplaException {
super(sm);
IOInterface printInterface = getService( IOInterface.class);
boolean applet =(getService(StartupEnvironment.class)).getStartupMode() == StartupEnvironment.APPLET;
if (printInterface.supportsPostscriptExport() && !applet) {
PSExportService exportService = new PSExportService(getContext());
addService("psexport",exportService);
}
if (!applet) {
PDFExportService exportService = new PDFExportService(getContext());
addService("pdf",exportService);
}
}
public boolean export(Printable printable,PageFormat pageFormat,Component parentComponent) throws Exception
{
Collection<ExportService> services = exporters.values();
Object[] serviceArray = services.toArray();
@SuppressWarnings("unchecked")
JList list = new JList(serviceArray);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
panel.add(new JLabel(getString("weekview.print.choose_export")),BorderLayout.NORTH);
panel.add(list,BorderLayout.CENTER);
setRenderer(list);
list.setSelectedIndex(0);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
DialogUI dlg = DialogUI.create(getContext(),parentComponent,true,panel,
new String[] {
getString("export")
,getString("cancel")
});
dlg.setTitle(getString("weekview.print.choose_export"));
dlg.getButton(0).setIcon(getIcon("icon.save"));
dlg.getButton(1).setIcon(getIcon("icon.cancel"));
dlg.start();
if (dlg.getSelectedIndex() != 0 || list.getSelectedIndex() == -1)
return false;
ExportService selectedService = (ExportService)serviceArray[list.getSelectedIndex()];
boolean result = selectedService.export(printable,pageFormat, parentComponent);
return result;
}
@SuppressWarnings("unchecked")
private void setRenderer(JList list) {
list.setCellRenderer(new NamedListCellRenderer(getI18n().getLocale()));
}
public void addService(Object policy,ExportService exportService) {
exporters.put(policy, exportService);
}
public void removeService(Object policy) {
exporters.remove(policy);
}
public ExportService select(Object policy) throws RaplaContextException {
ExportService result = exporters.get(policy);
if (result == null)
throw new RaplaContextException("Export Service not found for key " + policy);
return result;
}
public boolean isSelectable(Object policy) {
return exporters.get(policy) != null;
}
public ExportService[] getServices() {
return exporters.values().toArray(new ExportService[0]);
}
}
| 04900db4-rob | src/org/rapla/gui/internal/print/ExportServiceList.java | Java | gpl3 | 4,959 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.print;
import java.awt.Component;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.util.Locale;
import org.rapla.components.iolayer.IOInterface;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.RaplaGUIComponent;
public class PSExportService extends RaplaGUIComponent implements ExportService {
public final static String EXPORT_DIR = PSExportService.class.getName() + ".dir";
IOInterface printInterface;
public PSExportService(RaplaContext sm){
super(sm);
printInterface = getService(IOInterface.class);
}
public boolean export(Printable printable,PageFormat pageFormat,Component parentComponent) throws Exception
{
String dir = (String) getSessionMap().get(EXPORT_DIR);
boolean isPDF = false;
String file = printInterface.saveAsFileShowDialog
(
dir
,printable
,pageFormat
,false
,parentComponent
,isPDF
);
if (file != null)
{
getSessionMap().put(EXPORT_DIR,file);
return true;
}
else
{
return false;
}
}
public String getName(Locale locale) {
return getI18n().getString("weekview.print.postscript");
}
}
| 04900db4-rob | src/org/rapla/gui/internal/print/PSExportService.java | Java | gpl3 | 2,364 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.print;
import java.awt.Component;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
public interface ExportService extends org.rapla.entities.Named {
boolean export(Printable printable,PageFormat pageFormat,Component parentComponent) throws Exception;
}
| 04900db4-rob | src/org/rapla/gui/internal/print/ExportService.java | Java | gpl3 | 1,247 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JToolBar;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.User;
import org.rapla.entities.domain.Permission;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.ModificationEvent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.action.SaveableToggleAction;
import org.rapla.gui.internal.common.InternMenus;
import org.rapla.gui.internal.common.MultiCalendarView;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaMenu;
import org.rapla.gui.toolkit.RaplaMenuItem;
import org.rapla.gui.toolkit.RaplaWidget;
import org.rapla.storage.UpdateResult;
final public class CalendarEditor extends RaplaGUIComponent implements RaplaWidget {
public static final TypedComponentRole<Boolean> SHOW_CONFLICTS_CONFIG_ENTRY = new TypedComponentRole<Boolean>("org.rapla.showConflicts");
public static final TypedComponentRole<Boolean> SHOW_SELECTION_CONFIG_ENTRY = new TypedComponentRole<Boolean>("org.rapla.showSelection");
public static final String SHOW_SELECTION_MENU_ENTRY = "show_resource_selection";
public static final String SHOW_CONFLICTS_MENU_ENTRY = "show_conflicts";
RaplaMenuItem ownReservationsMenu;
JSplitPane content = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
final private ResourceSelection resourceSelection;
final private SavedCalendarView savedViews;
final private ConflictSelection conflictsView;
final public MultiCalendarView calendarContainer;
final JToolBar minimized;
final JToolBar templatePanel;
final JPanel left;
boolean listenersDisabled = false;
public CalendarEditor(RaplaContext context, final CalendarSelectionModel model) throws RaplaException {
super(context);
calendarContainer = new MultiCalendarView(getContext(), model, this);
calendarContainer.addValueChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e) {
if ( listenersDisabled)
{
return;
}
try {
resourceSelection.updateMenu();
} catch (RaplaException e1) {
getLogger().error(e1.getMessage(), e1);
}
}
});
resourceSelection = new ResourceSelection(context, calendarContainer, model);
final ChangeListener treeListener = new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if ( listenersDisabled)
{
return;
}
conflictsView.clearSelection();
}
};
final RaplaMenu viewMenu = getService( InternMenus.VIEW_MENU_ROLE);
ownReservationsMenu = new RaplaMenuItem("only_own_reservations");
ownReservationsMenu.setText( getString("only_own_reservations"));
ownReservationsMenu = new RaplaMenuItem("only_own_reservations");
ownReservationsMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean isSelected = model.isOnlyCurrentUserSelected();
// switch selection options
model.setOption( CalendarModel.ONLY_MY_EVENTS, isSelected ? "false":"true");
updateOwnReservationsSelected();
try {
Entity preferences = getQuery().getPreferences();
UpdateResult modificationEvt = new UpdateResult( getUser());
modificationEvt.addOperation( new UpdateResult.Change(preferences, preferences));
resourceSelection.dataChanged(modificationEvt);
calendarContainer.update(modificationEvt);
conflictsView.dataChanged( modificationEvt);
} catch (Exception ex) {
showException(ex, getComponent());
}
}
});
ownReservationsMenu.setText( getString("only_own_reservations"));
ownReservationsMenu.setIcon( getIcon("icon.unchecked"));
updateOwnReservationsSelected();
viewMenu.insertBeforeId( ownReservationsMenu, "show_tips" );
resourceSelection.getTreeSelection().addChangeListener( treeListener);
conflictsView = new ConflictSelection(context, calendarContainer, model);
left = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridheight = 1;
c.gridx = 1;
c.gridy = 1;
c.weightx = 0;
c.weighty = 0;
c.anchor = GridBagConstraints.EAST;
final JButton max = new JButton();
final JButton tree = new JButton();
tree.setEnabled( false );
minimized = new JToolBar(JToolBar.VERTICAL);
minimized.setFloatable( false);
minimized.add( max);
minimized.add( tree);
max.setIcon( UIManager.getDefaults().getIcon("InternalFrame.maximizeIcon"));
tree.setIcon( getIcon("icon.tree"));
JButton min = new RaplaButton(RaplaButton.SMALL);
ActionListener minmaxAction = new ActionListener() {
public void actionPerformed(ActionEvent e) {
savedViews.closeFilter();
int index = viewMenu.getIndexOfEntryWithId(SHOW_SELECTION_MENU_ENTRY);
JMenuItem component = (JMenuItem)viewMenu.getMenuComponent( index);
((SaveableToggleAction)component.getAction()).toggleCheckbox( component);
}
};
min.addActionListener( minmaxAction);
max.addActionListener( minmaxAction);
tree.addActionListener( minmaxAction);
templatePanel = new JToolBar(JToolBar.VERTICAL);
templatePanel.setFloatable( false);
final JButton exitTemplateEdit = new JButton();
//exitTemplateEdit.setIcon(getIcon("icon.close"));
exitTemplateEdit.setText(getString("close-template"));
templatePanel.add( exitTemplateEdit);
exitTemplateEdit.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
getModification().setTemplateName( null );
}
});
Icon icon = UIManager.getDefaults().getIcon("InternalFrame.minimizeIcon");
min.setIcon( icon) ;
//left.add(min, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1;
c.gridy = 1;
JPanel jp = new JPanel();
jp.setLayout( new BorderLayout());
savedViews = new SavedCalendarView(context, calendarContainer, resourceSelection,model);
jp.add( savedViews.getComponent(), BorderLayout.CENTER );
templatePanel.setVisible( false);
jp.add( templatePanel, BorderLayout.WEST );
JToolBar mintb =new JToolBar();
mintb.setFloatable( false);
// mintb.add( min);
min.setAlignmentY( JButton.TOP);
jp.add( min, BorderLayout.EAST);
left.add(jp, c);
c.fill = GridBagConstraints.BOTH;
c.gridy = 2;
c.weightx = 1;
c.weighty = 2.5;
left.add(resourceSelection.getComponent(), c);
c.weighty = 1.0;
c.gridy = 3;
left.add(conflictsView.getComponent(), c);
c.weighty = 0.0;
c.fill = GridBagConstraints.NONE;
c.gridy = 4;
c.anchor = GridBagConstraints.WEST;
left.add(conflictsView.getSummaryComponent(), c);
content.setRightComponent(calendarContainer.getComponent());
updateViews();
}
public void updateOwnReservationsSelected()
{
final CalendarSelectionModel model = resourceSelection.getModel();
boolean isSelected = model.isOnlyCurrentUserSelected();
ownReservationsMenu.setIcon(isSelected ? getIcon("icon.checked") : getIcon("icon.unchecked"));
ownReservationsMenu.setSelected(isSelected);
boolean canSeeEventsFromOthers = canSeeEventsFromOthers();
ownReservationsMenu.setEnabled( canSeeEventsFromOthers);
if ( !canSeeEventsFromOthers && !isSelected)
{
model.setOption(CalendarModel.ONLY_MY_EVENTS, "true");
}
}
private boolean canSeeEventsFromOthers() {
try {
Category category = getQuery().getUserGroupsCategory().getCategory(Permission.GROUP_CAN_READ_EVENTS_FROM_OTHERS);
if (category == null) {
return true;
}
User user = getUser();
return user.isAdmin() || user.belongsTo(category);
} catch (RaplaException ex) {
return false;
}
}
public void dataChanged(ModificationEvent evt) throws RaplaException {
listenersDisabled = true;
try
{
resourceSelection.dataChanged(evt);
calendarContainer.update(evt);
savedViews.update();
conflictsView.dataChanged(evt);
updateViews();
// this is done in calendarContainer update
//updateOwnReservationsSelected();
}
finally
{
listenersDisabled = false;
}
}
private void updateViews() throws RaplaException {
boolean showConflicts = getClientFacade().getPreferences().getEntryAsBoolean( SHOW_CONFLICTS_CONFIG_ENTRY, true);
boolean showSelection = getClientFacade().getPreferences().getEntryAsBoolean( SHOW_SELECTION_CONFIG_ENTRY, true);
conflictsView.getComponent().setVisible( showConflicts);
conflictsView.getSummaryComponent().setVisible( !showConflicts );
boolean templateMode = getModification().getTemplateName() != null;
if ( templateMode)
{
conflictsView.getComponent().setVisible(false);
conflictsView.getSummaryComponent().setVisible( false);
}
// if ( templateMode)
// {
// if ( content.getLeftComponent() != templatePanel)
// {
// content.setLeftComponent( templatePanel);
// content.setDividerSize(0);
// }
// }
// else
// {
if ( showSelection )
{
savedViews.getComponent().setVisible( !templateMode );
templatePanel.setVisible( templateMode);
resourceSelection.getFilterButton().setVisible( !templateMode );
if ( content.getLeftComponent() != left )
{
content.setLeftComponent( left);
content.setDividerSize( 5);
content.setDividerLocation(285);
}
}
else if ( content.getLeftComponent() != minimized)
{
content.setLeftComponent( minimized);
content.setDividerSize(0);
}
// }
}
public void start() {
calendarContainer.getSelectedCalendar().scrollToStart();
}
public JComponent getComponent() {
return content;
}
}
| 04900db4-rob | src/org/rapla/gui/internal/CalendarEditor.java | Java | gpl3 | 12,075 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.action;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaAction;
import org.rapla.gui.ReservationController;
import org.rapla.gui.ReservationEdit;
public class AppointmentAction extends RaplaAction {
public final static int DELETE = 1;
public final static int COPY = 2;
public final static int PASTE = 3;
public final static int CUT = 4;
public final static int EDIT = 6;
public final static int VIEW = 7;
public final static int CHANGE_ALLOCATABLE = 8;
public final static int ADD_TO_RESERVATION = 9;
public final static int PASTE_AS_NEW = 10;
public final static int DELETE_SELECTION = 11;
private boolean keepTime = false;
Component parent;
Point point;
int type;
AppointmentBlock appointmentBlock;
ReservationEdit reservationEdit;
// ReservationWizard wizard;
private Collection<Allocatable> contextAllocatables;
public AppointmentAction(RaplaContext context,Component parent,Point point)
{
super( context);
this.parent = parent;
this.point = point;
}
public AppointmentAction setAddTo(ReservationEdit reservationEdit)
{
this.reservationEdit = reservationEdit;
this.type = ADD_TO_RESERVATION;
String name2 = getName(reservationEdit.getReservation());
String value = name2.trim().length() > 0 ? "'" + name2 + "'" : getString("new_reservation");
putValue(NAME, value);
putValue(SMALL_ICON, getIcon("icon.new"));
boolean canAllocate = canAllocate();
setEnabled( canAllocate);
return this;
}
public AppointmentAction setCopy(AppointmentBlock appointmentBlock, Collection<Allocatable> contextAllocatables) {
this.appointmentBlock = appointmentBlock;
this.type = COPY;
this.contextAllocatables = contextAllocatables;
putValue(NAME, getString("copy"));
putValue(SMALL_ICON, getIcon("icon.copy"));
setEnabled(canCreateReservation());
return this;
}
public AppointmentAction setPaste( boolean keepTime) {
this.type = PASTE;
this.keepTime = keepTime;
putValue(NAME, getString("paste_into_existing_event"));
putValue(SMALL_ICON, getIcon("icon.paste"));
setEnabled(isAppointmentOnClipboard() && canCreateReservation());
return this;
}
public AppointmentAction setPasteAsNew( boolean keepTime) {
this.keepTime = keepTime;
this.type = PASTE_AS_NEW;
putValue(NAME, getString("paste_as") + " " + getString( "new_reservation" ) );
putValue(SMALL_ICON, getIcon("icon.paste_new"));
setEnabled(isAppointmentOnClipboard() && canCreateReservation());
return this;
}
/**
* Context menu entry to delete an appointment.
*/
public AppointmentAction setDelete(AppointmentBlock appointmentBlock){
this.appointmentBlock = appointmentBlock;
Appointment appointment = appointmentBlock.getAppointment();
this.type = DELETE;
putValue(NAME, getI18n().format("delete.format", getString("appointment")));
putValue(SMALL_ICON, getIcon("icon.delete"));
setEnabled(canModify(appointment.getReservation()));
return this;
}
public AppointmentAction setDeleteSelection(Collection<AppointmentBlock> selection) {
this.type = DELETE_SELECTION;
putValue(NAME, getString("delete_selection"));
putValue(SMALL_ICON, getIcon("icon.delete"));
changeSelection( selection );
return this;
}
Collection<AppointmentBlock> blockList;
private void changeSelection(Collection<AppointmentBlock> blockList) {
this.blockList = blockList;
if (type == DELETE_SELECTION) {
boolean enabled = true;
if (blockList != null && blockList.size() > 0 ) {
Iterator<AppointmentBlock> it = blockList.iterator();
while (it.hasNext()) {
if (!canModify(it.next().getAppointment().getReservation())){
enabled = false;
break;
}
}
} else {
enabled = false;
}
setEnabled(enabled);
}
}
public AppointmentAction setView(AppointmentBlock appointmentBlock) {
this.appointmentBlock = appointmentBlock;
Appointment appointment = appointmentBlock.getAppointment();
this.type = VIEW;
putValue(NAME, getString("view"));
putValue(SMALL_ICON, getIcon("icon.help"));
try
{
User user = getUser();
boolean canRead = canRead(appointment, user);
setEnabled( canRead);
}
catch (RaplaException ex)
{
getLogger().error( "Can't get user",ex);
}
return this;
}
public AppointmentAction setEdit(AppointmentBlock appointmentBlock) {
this.appointmentBlock = appointmentBlock;
this.type = EDIT;
putValue(SMALL_ICON, getIcon("icon.edit"));
Appointment appointment = appointmentBlock.getAppointment();
boolean canExchangeAllocatables = getQuery().canExchangeAllocatables(appointment.getReservation());
boolean canModify = canModify(appointment.getReservation());
String text = !canModify && canExchangeAllocatables ? getString("exchange_allocatables") : getString("edit");
putValue(NAME, text);
setEnabled(canModify || canExchangeAllocatables );
return this;
}
public void actionPerformed(ActionEvent evt) {
try {
switch (type) {
case DELETE: delete();break;
case COPY: copy();break;
case PASTE: paste(false);break;
case PASTE_AS_NEW: paste( true);break;
// case NEW: newReservation();break;
case ADD_TO_RESERVATION: addToReservation();break;
case EDIT: edit();break;
case VIEW: view();break;
case DELETE_SELECTION: deleteSelection();break;
}
} catch (RaplaException ex) {
showException(ex,parent);
} // end of try-catch
}
private void deleteSelection() throws RaplaException {
if ( this.blockList == null){
return;
}
getReservationController().deleteBlocks(blockList,parent,point);
}
public void view() throws RaplaException {
Appointment appointment = appointmentBlock.getAppointment();
getInfoFactory().showInfoDialog(appointment.getReservation(),parent,point);
}
public void edit() throws RaplaException {
getReservationController().edit( appointmentBlock);
}
private void delete() throws RaplaException {
getReservationController().deleteAppointment(appointmentBlock,parent,point);
}
private void copy() throws RaplaException
{
getReservationController().copyAppointment(appointmentBlock,parent,point, contextAllocatables);
}
private void paste(boolean asNewReservation) throws RaplaException {
ReservationController reservationController = getReservationController();
CalendarSelectionModel model = getService( CalendarSelectionModel.class);
Date start = getStartDate(model);
reservationController.pasteAppointment( start
,parent
,point
,asNewReservation, keepTime);
}
private void addToReservation() throws RaplaException
{
CalendarSelectionModel model = getService( CalendarSelectionModel.class);
Date start = getStartDate(model);
Date end = getEndDate(model, start);
reservationEdit.addAppointment(start,end);
}
public boolean isAppointmentOnClipboard() {
return (getReservationController().isAppointmentOnClipboard());
}
}
| 04900db4-rob | src/org/rapla/gui/internal/action/AppointmentAction.java | Java | gpl3 | 9,329 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.action;
import java.awt.Component;
import java.awt.Point;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
public class DynamicTypeAction extends RaplaObjectAction {
String classificationType;
public DynamicTypeAction(RaplaContext sm,Component parent) {
super(sm,parent);
}
public DynamicTypeAction(RaplaContext sm,Component parent,Point p) {
super(sm,parent,p);
}
public DynamicTypeAction setNewClassificationType(String classificationType) {
this.classificationType = classificationType;
super.setNew( null );
return this;
}
protected void newEntity() throws RaplaException {
DynamicType newDynamicType = getModification().newDynamicType(classificationType);
getEditController().edit(newDynamicType, parent);
}
}
| 04900db4-rob | src/org/rapla/gui/internal/action/DynamicTypeAction.java | Java | gpl3 | 1,858 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.action;
import java.awt.event.ActionEvent;
import javax.swing.SwingUtilities;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaAction;
import org.rapla.storage.dbrm.RestartServer;
public class RestartServerAction extends RaplaAction {
/**
* @param sm
* @throws RaplaException
*/
public RestartServerAction(RaplaContext sm) throws RaplaException {
super(sm);
putValue(NAME,getString("restart_server"));
putValue(SMALL_ICON,getIcon("icon.restart"));
}
public void actionPerformed(ActionEvent arg0) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
try {
RestartServer service = getService( RestartServer.class);
service.restartServer();
} catch (RaplaException ex) {
getLogger().error("Error restarting ", ex);
}
}
});
}
}
| 04900db4-rob | src/org/rapla/gui/internal/action/RestartServerAction.java | Java | gpl3 | 1,967 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.action.user;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import org.rapla.client.ClientService;
import org.rapla.entities.User;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.EditComponent;
import org.rapla.gui.RaplaAction;
import org.rapla.gui.internal.edit.EditDialog;
public class UserAction extends RaplaAction {
Object object;
Component parent;
public final int NEW = 1;
public final int SWITCH_TO_USER = 3;
int type = NEW;
Point point;
public UserAction(RaplaContext sm,Component parent,Point point) {
super( sm);
this.parent = parent;
this.point = point;
}
public UserAction setNew() {
type = NEW;
putValue(NAME, getString("user"));
putValue(SMALL_ICON, getIcon("icon.new"));
update();
return this;
}
public UserAction setSwitchToUser() {
type = SWITCH_TO_USER;
ClientService service = getService( ClientService.class);
if (service.canSwitchBack()) {
putValue(NAME, getString("switch_back"));
} else {
putValue(NAME, getString("switch_to"));
}
return this;
}
public void changeObject(Object object) {
this.object = object;
update();
}
private void update() {
User user = null;
try {
user = getUser();
if (type == NEW) {
setEnabled(isAdmin());
} else if (type == SWITCH_TO_USER) {
ClientService service = getService( ClientService.class);
setEnabled(service.canSwitchBack() ||
(object != null && isAdmin() && !user.equals(object )));
}
} catch (RaplaException ex) {
setEnabled(false);
return;
}
}
public void actionPerformed(ActionEvent evt) {
try {
if (type == SWITCH_TO_USER) {
ClientService service = getService( ClientService.class);
if (service.canSwitchBack()) {
service.switchTo(null);
//putValue(NAME, getString("switch_to"));
} else if ( object != null ){
service.switchTo((User) object);
// putValue(NAME, getString("switch_back"));
}
} else if (type == NEW) {
User newUser = getModification().newUser();
EditComponent<User> ui = getEditController().createUI( newUser);
EditDialog<User> gui = new EditDialog<User>(getContext(),ui);
List<User> singletonList = new ArrayList<User>();
singletonList.add(newUser);
if (gui.start( singletonList ,getString("user"), parent) == 0
&& getUserModule().canChangePassword() )
changePassword(newUser,false);
object = newUser;
}
} catch (RaplaException ex) {
showException(ex, this.parent);
}
}
public void changePassword(User user,boolean showOld) throws RaplaException{
new PasswordChangeAction(getContext(),parent).changePassword( user, showOld);
}
}
| 04900db4-rob | src/org/rapla/gui/internal/action/user/UserAction.java | Java | gpl3 | 4,319 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.action.user;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.toolkit.RaplaWidget;
public class PasswordChangeUI extends RaplaGUIComponent
implements
RaplaWidget
{
JPanel superPanel = new JPanel();
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
GridLayout gridLayout1 = new GridLayout();
// The Controller for this Dialog
JLabel label1 = new JLabel();
JLabel label2 = new JLabel();
JLabel label3 = new JLabel();
JPasswordField tf1 = new JPasswordField(10);
JPasswordField tf2 = new JPasswordField(10);
JPasswordField tf3 = new JPasswordField(10);
public PasswordChangeUI(RaplaContext sm) {
this(sm,true);
}
public PasswordChangeUI(RaplaContext sm,boolean askForOldPassword) {
super( sm);
superPanel.setLayout(new BoxLayout(superPanel, BoxLayout.Y_AXIS));
panel2.add(new JLabel(getString("password_change_info")));
panel.setLayout(gridLayout1);
gridLayout1.setRows(askForOldPassword ? 4 : 3);
gridLayout1.setColumns(2);
gridLayout1.setHgap(10);
gridLayout1.setVgap(10);
if (askForOldPassword) {
panel.add(label1);
panel.add(tf1);
}
panel.add(label2);
panel.add(tf2);
panel.add(label3);
panel.add(tf3);
label1.setText(getString("old_password") + ":");
label2.setText(getString("new_password") + ":");
label3.setText(getString("password_verification") + ":");
final JCheckBox showPassword = new JCheckBox(getString("show_password"));
panel.add( showPassword);
showPassword.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean show = showPassword.isSelected();
tf1.setEchoChar( show ? ((char) 0): '*');
tf2.setEchoChar( show ? ((char) 0): '*');
tf3.setEchoChar( show ? ((char) 0): '*');
}
});
superPanel.add(panel);
superPanel.add(panel2);
}
public JComponent getComponent() {
return superPanel;
}
public char[] getOldPassword() {
return tf1.getPassword();
}
public char[] getNewPassword() {
return tf2.getPassword();
}
public char[] getPasswordVerification() {
return tf3.getPassword();
}
}
| 04900db4-rob | src/org/rapla/gui/internal/action/user/PasswordChangeUI.java | Java | gpl3 | 3,624 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.action.user;
import java.awt.Component;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import org.rapla.components.util.Tools;
import org.rapla.entities.User;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaAction;
import org.rapla.gui.toolkit.DialogUI;
public class PasswordChangeAction extends RaplaAction {
Object object;
Component parent;
public PasswordChangeAction(RaplaContext context,Component parent) {
super( context);
this.parent = parent;
putValue(NAME, getI18n().format("change.format",getString("password")));
}
public void changeObject(Object object) {
this.object = object;
update();
}
private void update() {
User user = null;
try {
user = getUser();
setEnabled(object != null && (isAdmin() || user.equals(object)));
} catch (RaplaException ex) {
setEnabled(false);
return;
}
}
public void actionPerformed(ActionEvent evt) {
try {
if (object == null)
return;
changePassword((User) object, !getUser().isAdmin());
} catch (RaplaException ex) {
showException(ex, this.parent);
}
}
public void changePassword(User user,boolean showOld) throws RaplaException{
new PasswordChangeActionA(user,showOld).start();
}
class PasswordChangeActionA extends AbstractAction {
private static final long serialVersionUID = 1L;
PasswordChangeUI ui;
DialogUI dlg;
User user;
boolean showOld;
PasswordChangeActionA(User user,boolean showOld) {
this.user = user;
this.showOld = showOld;
putValue(NAME, getString("change"));
}
public void start() throws RaplaException
{
ui = new PasswordChangeUI(getContext(),showOld);
dlg = DialogUI.create(getContext(),parent,true,ui.getComponent(),new String[] {getString("change"),getString("cancel")});
dlg.setDefault(0);
dlg.setTitle(getI18n().format("change.format",getString("password")));
dlg.getButton(0).setAction(this);
dlg.getButton(1).setIcon(getIcon("icon.cancel"));
dlg.start();
}
public void actionPerformed(ActionEvent evt) {
try {
char[] oldPassword = showOld ? ui.getOldPassword() : new char[0];
char[] p1= ui.getNewPassword();
char[] p2= ui.getPasswordVerification();
if (!Tools.match(p1,p2))
throw new RaplaException(getString("error.passwords_dont_match"));
getUserModule().changePassword(user , oldPassword, p1);
dlg.close();
} catch (RaplaException ex) {
showException(ex,dlg);
}
}
}
}
| 04900db4-rob | src/org/rapla/gui/internal/action/user/PasswordChangeAction.java | Java | gpl3 | 3,969 |
<body>
Actions can be reused with menus, popups or buttons.
</body>
| 04900db4-rob | src/org/rapla/gui/internal/action/package.html | HTML | gpl3 | 71 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.action;
import java.awt.Component;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.rapla.entities.Category;
import org.rapla.entities.Entity;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Period;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.dynamictype.Classifiable;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.facade.ModificationModule;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaAction;
import org.rapla.gui.internal.edit.DeleteUndo;
import org.rapla.gui.toolkit.DialogUI;
public class RaplaObjectAction extends RaplaAction {
public final static int DELETE = 1;
public final static int COPY = 2;
public final static int PASTE = 3;
public final static int CUT = 4;
public final static int NEW = 5;
public final static int EDIT = 6;
public final static int VIEW = 7;
public final static int DELETE_SELECTION = 8;
public final static int EDIT_SELECTION = 9; // new attribute to define a
// edit selection (several
// editable entities)
protected Component parent;
Point point;
protected int type;
boolean isPerson;
protected Entity<?> object;
Collection<Entity<?>> objectList;
protected RaplaType raplaType;
public RaplaObjectAction(RaplaContext sm) {
this(sm,null);
}
public RaplaObjectAction(RaplaContext sm,Component parent) {
this(sm,parent,null);
}
public RaplaObjectAction(RaplaContext sm,Component parent,Point point) {
super( sm);
this.parent = parent;
this.point = point;
}
public RaplaObjectAction setNew(RaplaType raplaType) {
this.raplaType = raplaType;
this.type = NEW;
putValue(NAME, getString("new"));
putValue(SMALL_ICON, getIcon("icon.new"));
update();
return this;
}
public RaplaObjectAction setDelete(Entity<?> object) {
this.type = DELETE;
putValue(NAME, getString("delete"));
putValue(SMALL_ICON, getIcon("icon.delete"));
changeObject(object);
return this;
}
public RaplaObjectAction setDeleteSelection(Collection<Entity<?>> selection) {
this.type = DELETE_SELECTION;
putValue(NAME, getString("delete_selection"));
putValue(SMALL_ICON, getIcon("icon.delete"));
this.objectList = new ArrayList<Entity<?>>(selection);
update();
return this;
}
public RaplaObjectAction setView(Entity<?> object) {
this.type = VIEW;
putValue(NAME, getString("view"));
putValue(SMALL_ICON, getIcon("icon.help"));
changeObject(object);
return this;
}
public RaplaObjectAction setEdit(Entity<?> object) {
this.type = EDIT;
putValue(NAME, getString("edit"));
putValue(SMALL_ICON, getIcon("icon.edit"));
changeObject(object);
return this;
}
// method for setting a selection as a editable selection
// (cf. setEdit() and setDeleteSelection())
public RaplaObjectAction setEditSelection(Collection<Entity<?>> selection) {
this.type = EDIT_SELECTION;
putValue(NAME, getString("edit"));
putValue(SMALL_ICON, getIcon("icon.edit"));
this.objectList = new ArrayList<Entity<?>>(selection);
update();
return this;
}
public void changeObject(Entity<?> object) {
this.object = object;
if (type == DELETE) {
if (object == null)
putValue(NAME, getString("delete"));
else
putValue(NAME, getI18n().format("delete.format",getName(object)));
}
update();
}
protected void update() {
boolean enabled = true;
if (type == EDIT || type == DELETE) {
enabled = canModify(object);
} else if (type == NEW ) {
enabled = (raplaType != null && raplaType.is(Allocatable.TYPE) && isRegisterer()) || isAdmin();
} else if (type == EDIT_SELECTION || type == DELETE_SELECTION) {
if (objectList != null && objectList.size() > 0 ) {
Iterator<Entity<?>> it = objectList.iterator();
while (it.hasNext()) {
if (!canModify(it.next())){
enabled = false;
break;
}
}
} else {
enabled = false;
}
}
setEnabled(enabled);
}
public void actionPerformed(ActionEvent evt) {
try {
switch (type) {
case DELETE: delete();break;
case DELETE_SELECTION: deleteSelection();break;
case EDIT: edit();break;
// EditSelection() as reaction of actionPerformed (click on the edit
// button)
case EDIT_SELECTION:editSelection();break;
case NEW: newEntity();break;
case VIEW: view();break;
}
} catch (RaplaException ex) {
showException(ex,parent);
} // end of try-catch
}
public void view() throws RaplaException {
getInfoFactory().showInfoDialog(object,parent);
}
protected Entity<? extends Entity<?>> newEntity(RaplaType raplaType) throws RaplaException {
ModificationModule m = getModification();
if ( Reservation.TYPE.is( raplaType ))
{
DynamicType type = guessType();
final Classification newClassification = type.newClassification();
Reservation newReservation = m.newReservation( newClassification );
return newReservation;
}
if ( Allocatable.TYPE.is( raplaType ))
{
DynamicType type = guessType();
final Classification newClassification = type.newClassification();
Allocatable allocatable = m.newAllocatable( newClassification );
return allocatable ;
}
if ( Category.TYPE.is( raplaType ))
return m.newCategory(); //will probably never happen
if ( User.TYPE.is( raplaType ))
return m.newUser();
if ( Period.TYPE.is( raplaType ))
return m.newPeriod();
throw new RaplaException("Can't create Entity for " + raplaType + "!");
}
/** guesses the DynamicType for the new object depending on the selected element.
<li>If the selected element is a DynamicType-Folder the DynamicType will be returned.
<li>If the selected element has a Classification the appropriatie DynamicType will be returned.
<li>else the first matching DynamicType for the passed classificationType will be returned.
<li>null if none of the above criterias matched.
*/
public DynamicType guessType() throws RaplaException {
DynamicType[] types = guessTypes();
if ( types.length > 0)
{
return types[0];
}
else
{
return null;
}
}
public DynamicType[] guessTypes() throws RaplaException {
DynamicType dynamicType = null;
getLogger().debug("Guessing DynamicType from " + object);
if (object instanceof DynamicType)
dynamicType = (DynamicType) object;
if (object instanceof Classifiable) {
Classification classification= ((Classifiable) object).getClassification();
dynamicType = classification.getType();
}
if (dynamicType != null)
{
return new DynamicType[] {dynamicType};
}
String classificationType = null;
if ( Reservation.TYPE.is( raplaType )) {
classificationType = DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION;
} else if ( Allocatable.TYPE.is( raplaType )) {
if ( isPerson ) {
classificationType = DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON;
} else {
classificationType = DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE;
}
}
DynamicType[] dynamicTypes = getQuery().getDynamicTypes( classificationType );
return dynamicTypes;
}
protected void newEntity() throws RaplaException {
if ( Category.TYPE.is( raplaType )) {
Category category = (Category)object;
getEditController().editNew(category, parent );
} else {
Entity<? extends Entity> obj = newEntity(raplaType);
getEditController().edit(obj, parent);
}
}
protected void edit() throws RaplaException {
getEditController().edit(object, parent);
}
protected void delete() throws RaplaException {
if (object == null)
return;
Entity<?>[] objects = new Entity[] { object};
DialogUI dlg = getInfoFactory().createDeleteDialog( objects, parent);
dlg.start();
if (dlg.getSelectedIndex() != 0)
return;
List<Entity<?>> singletonList = Arrays.asList( objects);
delete(singletonList);
}
protected void deleteSelection() throws RaplaException
{
if (objectList == null || objectList.size() == 0)
return;
DialogUI dlg = getInfoFactory().createDeleteDialog(objectList.toArray(), parent);
dlg.start();
if (dlg.getSelectedIndex() != 0)
return;
delete(objectList);
}
protected void delete(Collection<Entity<?>> objects) throws RaplaException
{
Collection<Entity<?>> entities = new ArrayList<Entity<?>>();
boolean undoable = true;
for ( Entity<?> obj: objects)
{
entities.add( obj);
RaplaType<?> raplaType = obj.getRaplaType();
if ( raplaType == User.TYPE || raplaType == DynamicType.TYPE)
{
undoable = false;
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
DeleteUndo<? extends Entity<?>> deleteCommand = new DeleteUndo(getContext(), entities);
if ( undoable)
{
getModification().getCommandHistory().storeAndExecute(deleteCommand);
}
else
{
deleteCommand.execute();
}
}
// action which is executed by clicking on the edit button (after
// actionPerformed)
// chances the selection list in an array and commits it on EditController
protected void editSelection() throws RaplaException {
if (objectList == null || objectList.size() == 0)
return;
Entity[] array = objectList.toArray(Entity.ENTITY_ARRAY);
getEditController().edit(array, parent);
}
public void setPerson(boolean b) {
isPerson = b;
}
}
| 04900db4-rob | src/org/rapla/gui/internal/action/RaplaObjectAction.java | Java | gpl3 | 11,906 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.action;
import java.awt.event.ActionEvent;
import javax.swing.JMenuItem;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.TypedComponentRole;
import org.rapla.gui.RaplaAction;
import org.rapla.gui.toolkit.RaplaMenuItem;
public class SaveableToggleAction extends RaplaAction {
TypedComponentRole<Boolean> configEntry;
String name;
public SaveableToggleAction(RaplaContext context,String name,TypedComponentRole<Boolean> configEntry)
{
super( context );
this.name = name;
putValue( NAME, getString( name));
this.configEntry = configEntry;
//putValue(SMALL_ICON,getIcon("icon.unchecked"));
}
public RaplaMenuItem createMenuItem() throws RaplaException
{
RaplaMenuItem menu = new RaplaMenuItem(name);
menu.setAction( this);
final User user = getUser();
final Preferences preferences = getQuery().getPreferences( user );
boolean selected = preferences.getEntryAsBoolean( configEntry , true);
if(selected) {
menu.setSelected(true);
menu.setIcon(getIcon("icon.checked"));
}
else {
menu.setSelected(false);
menu.setIcon(getIcon("icon.unchecked"));
}
return menu;
}
public void actionPerformed(ActionEvent evt) {
toggleCheckbox((JMenuItem)evt.getSource());
}
public void toggleCheckbox(JMenuItem toolTip) {
boolean newSelected = !toolTip.isSelected();
if ( isModifyPreferencesAllowed())
{
try {
Preferences prefs = this.newEditablePreferences();
prefs.putEntry( configEntry, newSelected);
getModification().store( prefs);
} catch (Exception ex) {
showException( ex, null );
return;
}
}
toolTip.setSelected(newSelected);
javax.swing.ToolTipManager.sharedInstance().setEnabled(newSelected);
toolTip.setIcon(newSelected ? getIcon("icon.checked"):getIcon("icon.unchecked"));
}
}
| 04900db4-rob | src/org/rapla/gui/internal/action/SaveableToggleAction.java | Java | gpl3 | 3,159 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas, Bettina Lademann |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.action;
import java.awt.event.ActionEvent;
import org.rapla.client.ClientService;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.RaplaAction;
public class RestartRaplaAction extends RaplaAction{
public RestartRaplaAction(RaplaContext sm)
{
super(sm);
boolean logoutAvailable = getService(ClientService.class).isLogoutAvailable();
String string = getString("restart_client");
if (logoutAvailable)
{
string = getString("logout") +" / " + string;
}
putValue(NAME,string);
putValue(SMALL_ICON,getIcon("icon.restart"));
}
public void actionPerformed(ActionEvent arg0) {
boolean logoutAvailable = getService(ClientService.class).isLogoutAvailable();
if ( logoutAvailable)
{
getService(ClientService.class).logout();
}
else
{
getService(ClientService.class).restart();
}
}
}
| 04900db4-rob | src/org/rapla/gui/internal/action/RestartRaplaAction.java | Java | gpl3 | 1,932 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal;
import java.util.Locale;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import org.rapla.components.layout.TableLayout;
import org.rapla.entities.configuration.Preferences;
import org.rapla.facade.internal.CalendarOptionsImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.OptionPanel;
import org.rapla.gui.RaplaGUIComponent;
public class WarningsOption extends RaplaGUIComponent implements OptionPanel
{
JPanel panel = new JPanel();
Preferences preferences;
JCheckBox showConflictWarningsField = new JCheckBox();
public WarningsOption(RaplaContext sm) {
super( sm);
showConflictWarningsField.setText("");
double pre = TableLayout.PREFERRED;
panel.setLayout( new TableLayout(new double[][] {{pre, 5,pre}, {pre}}));
panel.add( new JLabel(getString("warning.conflict")),"0,0");
panel.add( showConflictWarningsField,"2,0");
}
public JComponent getComponent() {
return panel;
}
public String getName(Locale locale) {
return getString("warnings");
}
public void setPreferences( Preferences preferences) {
this.preferences = preferences;
}
public void show() throws RaplaException {
// get the options
boolean config = preferences.getEntryAsBoolean( CalendarOptionsImpl.SHOW_CONFLICT_WARNING, true);
showConflictWarningsField.setSelected( config);
}
public void commit() {
// Save the options
boolean selected = showConflictWarningsField.isSelected();
preferences.putEntry( CalendarOptionsImpl.SHOW_CONFLICT_WARNING, selected);
}
} | 04900db4-rob | src/org/rapla/gui/internal/WarningsOption.java | Java | gpl3 | 2,721 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2006 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal;
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.tree.DefaultTreeModel;
import org.rapla.components.calendar.RaplaArrowButton;
import org.rapla.components.layout.TableLayout;
import org.rapla.entities.Entity;
import org.rapla.entities.RaplaObject;
import org.rapla.entities.RaplaType;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Period;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.ModificationEvent;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.MenuContext;
import org.rapla.gui.MenuFactory;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.TreeFactory;
import org.rapla.gui.internal.action.RaplaObjectAction;
import org.rapla.gui.internal.common.InternMenus;
import org.rapla.gui.internal.common.MultiCalendarView;
import org.rapla.gui.internal.edit.ClassifiableFilterEdit;
import org.rapla.gui.internal.view.TreeFactoryImpl;
import org.rapla.gui.toolkit.PopupEvent;
import org.rapla.gui.toolkit.PopupListener;
import org.rapla.gui.toolkit.RaplaMenu;
import org.rapla.gui.toolkit.RaplaPopupMenu;
import org.rapla.gui.toolkit.RaplaTree;
import org.rapla.gui.toolkit.RaplaWidget;
public class ResourceSelection extends RaplaGUIComponent implements RaplaWidget {
protected JPanel content = new JPanel();
public RaplaTree treeSelection = new RaplaTree();
TableLayout tableLayout;
protected JPanel buttonsPanel = new JPanel();
protected final CalendarSelectionModel model;
MultiCalendarView view;
Listener listener = new Listener();
protected FilterEditButton filterEdit;
public ResourceSelection(RaplaContext context, MultiCalendarView view, CalendarSelectionModel model) throws RaplaException {
super(context);
this.model = model;
this.view = view;
/*double[][] sizes = new double[][] { { TableLayout.FILL }, { TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.FILL } };
tableLayout = new TableLayout(sizes);*/
content.setLayout(new BorderLayout());
content.add(treeSelection);
// content.setPreferredSize(new Dimension(260,400));
content.setBorder(BorderFactory.createRaisedBevelBorder());
content.add(buttonsPanel, BorderLayout.NORTH);
buttonsPanel.setLayout( new BorderLayout());
filterEdit = new FilterEditButton(context, model, listener,true);
buttonsPanel.add(filterEdit.getButton(), BorderLayout.EAST);
treeSelection.setToolTipRenderer(getTreeFactory().createTreeToolTipRenderer());
treeSelection.setMultiSelect(true);
treeSelection.getTree().setSelectionModel(((TreeFactoryImpl) getTreeFactory()).createComplexTreeSelectionModel());
updateTree();
updateSelection();
treeSelection.addChangeListener(listener);
treeSelection.addPopupListener(listener);
treeSelection.addDoubleclickListeners(listener);
treeSelection.getTree().addFocusListener(listener);
javax.swing.ToolTipManager.sharedInstance().registerComponent(treeSelection.getTree());
updateMenu();
}
protected HashSet<?> setSelectedObjects(){
HashSet<Object> elements = new HashSet<Object>(treeSelection.getSelectedElements());
getModel().setSelectedObjects(elements);
return elements;
}
public RaplaArrowButton getFilterButton() {
return filterEdit.getButton();
}
public RaplaTree getTreeSelection() {
return treeSelection;
}
protected CalendarSelectionModel getModel() {
return model;
}
public void dataChanged(ModificationEvent evt) throws RaplaException {
if ( evt != null && evt.isModified())
{
updateTree();
updateMenu();
}
// No longer needed here as directly done in RaplaClientServiceImpl
// ((CalendarModelImpl) model).dataChanged( evt);
}
final protected TreeFactory getTreeFactory() {
return getService(TreeFactory.class);
}
boolean treeListenersEnabled = true;
/*
* (non-Javadoc)
*
* @see org.rapla.gui.internal.view.ITreeFactory#createClassifiableModel(org.rapla.entities.dynamictype.Classifiable[], org.rapla.entities.dynamictype.DynamicType[])
*/
protected void updateTree() throws RaplaException {
treeSelection.getTree().setRootVisible(false);
treeSelection.getTree().setShowsRootHandles(true);
treeSelection.getTree().setCellRenderer(((TreeFactoryImpl) getTreeFactory()).createRenderer());
DefaultTreeModel treeModel = generateTree();
try {
treeListenersEnabled = false;
treeSelection.exchangeTreeModel(treeModel);
updateSelection();
} finally {
treeListenersEnabled = true;
}
}
protected DefaultTreeModel generateTree() throws RaplaException {
ClassificationFilter[] filter = getModel().getAllocatableFilter();
final TreeFactoryImpl treeFactoryImpl = (TreeFactoryImpl) getTreeFactory();
DefaultTreeModel treeModel = treeFactoryImpl.createModel(filter);
return treeModel;
}
protected void updateSelection() {
Collection<Object> selectedObjects = new ArrayList<Object>(getModel().getSelectedObjects());
treeSelection.select(selectedObjects);
}
public JComponent getComponent() {
return content;
}
protected MenuContext createMenuContext(Point p, Object obj) {
MenuContext menuContext = new MenuContext(getContext(), obj, getComponent(), p);
return menuContext;
}
protected void showTreePopup(PopupEvent evt) {
try {
Point p = evt.getPoint();
Object obj = evt.getSelectedObject();
List<?> list = treeSelection.getSelectedElements();
MenuContext menuContext = createMenuContext(p, obj);
menuContext.setSelectedObjects(list);
RaplaPopupMenu menu = new RaplaPopupMenu();
RaplaMenu newMenu = new RaplaMenu("new");
newMenu.setText(getString("new"));
boolean addNewReservationMenu = obj instanceof Allocatable || obj instanceof DynamicType;
((MenuFactoryImpl) getMenuFactory()).addNew(newMenu, menuContext, null, addNewReservationMenu);
getMenuFactory().addObjectMenu(menu, menuContext, "EDIT_BEGIN");
newMenu.setEnabled( newMenu.getMenuComponentCount() > 0);
menu.insertAfterId(newMenu, "EDIT_BEGIN");
JComponent component = (JComponent) evt.getSource();
menu.show(component, p.x, p.y);
} catch (RaplaException ex) {
showException(ex, getComponent());
}
}
class Listener implements PopupListener, ChangeListener, ActionListener, FocusListener {
public void showPopup(PopupEvent evt) {
showTreePopup(evt);
}
public void actionPerformed(ActionEvent evt) {
Object focusedObject = evt.getSource();
if ( focusedObject == null || !(focusedObject instanceof RaplaObject))
return;
// System.out.println(focusedObject.toString());
RaplaType type = ((RaplaObject) focusedObject).getRaplaType();
if ( type == User.TYPE
|| type == Allocatable.TYPE
|| type ==Period.TYPE
)
{
RaplaObjectAction editAction = new RaplaObjectAction( getContext(), getComponent(),null);
if (editAction.canModify( focusedObject))
{
editAction.setEdit((Entity<?>)focusedObject);
editAction.actionPerformed(null);
}
}
}
public void stateChanged(ChangeEvent evt) {
if (!treeListenersEnabled) {
return;
}
try {
Object source = evt.getSource();
ClassifiableFilterEdit filterUI = filterEdit.getFilterUI();
if ( filterUI != null && source == filterUI)
{
final ClassificationFilter[] filters = filterUI.getFilters();
model.setAllocatableFilter( filters);
updateTree();
applyFilter();
}
else if ( source == treeSelection)
{
updateChange();
}
} catch (Exception ex) {
showException(ex, getComponent());
}
}
public void focusGained(FocusEvent e) {
try {
if (!getUserModule().isSessionActive())
{
return;
}
updateMenu();
} catch (Exception ex) {
showException(ex, getComponent());
}
}
public void focusLost(FocusEvent e) {
}
}
public void updateChange() throws RaplaException {
setSelectedObjects();
updateMenu();
applyFilter();
}
public void applyFilter() throws RaplaException {
view.getSelectedCalendar().update();
}
public void updateMenu() throws RaplaException {
RaplaMenu editMenu = getService(InternMenus.EDIT_MENU_ROLE);
RaplaMenu newMenu = getService(InternMenus.NEW_MENU_ROLE);
editMenu.removeAllBetween("EDIT_BEGIN", "EDIT_END");
newMenu.removeAll();
List<?> list = treeSelection.getSelectedElements();
Object focusedObject = null;
if (list.size() == 1) {
focusedObject = treeSelection.getSelectedElement();
}
MenuContext menuContext = createMenuContext( null, focusedObject);
menuContext.setSelectedObjects(list);
if ( treeSelection.getTree().hasFocus())
{
getMenuFactory().addObjectMenu(editMenu, menuContext, "EDIT_BEGIN");
}
((MenuFactoryImpl) getMenuFactory()).addNew(newMenu, menuContext, null, true);
newMenu.setEnabled(newMenu.getMenuComponentCount() > 0 );
}
public MenuFactory getMenuFactory() {
return getService(MenuFactory.class);
}
}
| 04900db4-rob | src/org/rapla/gui/internal/ResourceSelection.java | Java | gpl3 | 11,749 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.rapla.client.internal.LanguageChooser;
import org.rapla.components.layout.TableLayout;
import org.rapla.entities.User;
import org.rapla.entities.configuration.Preferences;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.framework.RaplaLocale;
import org.rapla.gui.OptionPanel;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.action.user.PasswordChangeAction;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.RaplaButton;
public class UserOption extends RaplaGUIComponent
implements
OptionPanel
{
JPanel superPanel = new JPanel();
JLabel emailLabel = new JLabel();
JLabel nameLabel = new JLabel();
JLabel usernameLabel = new JLabel();
LanguageChooser languageChooser;
Preferences preferences;
public UserOption(RaplaContext sm) {
super(sm);
}
private void create() throws RaplaException {
superPanel.removeAll();
TableLayout tableLayout = new TableLayout(new double[][]{{TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.PREFERRED},{TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.PREFERRED}});
languageChooser= new LanguageChooser( getLogger(), getContext());
RaplaButton changeNameButton = new RaplaButton();
RaplaButton changeEmailButton = new RaplaButton();
RaplaButton changePasswordButton = new RaplaButton();
superPanel.setLayout(tableLayout);
superPanel.add( new JLabel(getString("language") + ": "),"0,0" );
superPanel.add( languageChooser.getComponent(),"2,0");
superPanel.add(new JLabel(getString("username") + ": "), "0,2");
superPanel.add(usernameLabel, "2,2");
superPanel.add(new JLabel(), "4,2");
superPanel.add(new JLabel(getString("name") + ": "), "0,4");
superPanel.add(nameLabel, "2,4");
superPanel.add(changeNameButton, "4,4");
superPanel.add(new JLabel(getString("email") + ": "), "0,6");
superPanel.add(emailLabel, "2,6");
superPanel.add(changeEmailButton, "4,6");
changeNameButton.setText(getString("change"));
changeNameButton.addActionListener(new MyActionListener());
nameLabel.setText(this.getClientFacade().getUser().getName());
emailLabel.setText(this.getClientFacade().getUser().getEmail());
changeEmailButton.setText(getString("change"));
changeEmailButton.addActionListener(new MyActionListener2( ));
superPanel.add(new JLabel(getString("password") + ":"), "0,8");
superPanel.add(new JLabel("****"), "2,8");
superPanel.add(changePasswordButton, "4,8");
PasswordChangeAction passwordChangeAction;
passwordChangeAction = new PasswordChangeAction(getContext(),getComponent());
User user = getUser();
passwordChangeAction.changeObject(user);
changePasswordButton.setAction(passwordChangeAction);
changePasswordButton.setText(getString("change"));
usernameLabel.setText(user.getUsername());
}
public void show() throws RaplaException {
create();
String language = preferences.getEntryAsString(RaplaLocale.LANGUAGE_ENTRY,null);
languageChooser.setSelectedLanguage( language);
}
public void setPreferences(Preferences preferences) {
this.preferences = preferences;
}
public void commit() {
String language = languageChooser.getSelectedLanguage();
preferences.putEntry( RaplaLocale.LANGUAGE_ENTRY,language );
}
public String getName(Locale locale) {
return getString("personal_options");
}
public JComponent getComponent() {
return superPanel;
}
class MyActionListener implements ActionListener{
public void actionPerformed(ActionEvent arg0)
{
try
{
JPanel test = new JPanel();
test.setLayout( new BorderLayout());
JPanel content = new JPanel();
GridLayout layout = new GridLayout();
layout.setColumns(2);
layout.setHgap(5);
layout.setVgap(5);
//content.setLayout(new TableLayout(new double[][]{{TableLayout.PREFERRED,5,TableLayout.PREFERRED},{TableLayout.PREFERRED,5,TableLayout.PREFERRED,5,TableLayout.PREFERRED, 5, TableLayout.PREFERRED}}));
content.setLayout( layout);
test.add(new JLabel(getString("enter_name")), BorderLayout.NORTH);
test.add(content, BorderLayout.CENTER);
User user = getUserModule().getUser();
Allocatable person = user.getPerson();
JTextField inputSurname = new JTextField();
addCopyPaste(inputSurname);
JTextField inputFirstname = new JTextField();
addCopyPaste(inputFirstname);
JTextField inputTitle= new JTextField();
addCopyPaste(inputTitle);
// Person connected?
if ( person != null)
{
Classification classification = person.getClassification();
DynamicType type = classification.getType();
Map<String,JTextField> map = new LinkedHashMap<String, JTextField>();
map.put("title", inputTitle);
map.put("firstname", inputFirstname);
map.put("forename", inputFirstname);
map.put("surname", inputSurname);
map.put("lastname", inputSurname);
int rows = 0;
for (Map.Entry<String, JTextField> entry: map.entrySet())
{
String fieldName = entry.getKey();
Attribute attribute = type.getAttribute(fieldName);
JTextField value = entry.getValue();
if ( attribute!= null && !content.isAncestorOf(value))
{
Locale locale = getLocale();
content.add( new JLabel(attribute.getName(locale)));
content.add( value);
Object value2 = classification.getValue( attribute);
rows++;
if ( value2 != null)
{
value.setText( value2.toString());
}
}
}
layout.setRows(rows); }
else
{
content.add( new JLabel(getString("name")));
content.add( inputSurname);
inputSurname.setText( user.getName());
layout.setRows(1);
}
DialogUI dlg = DialogUI.create(getContext(),getComponent(),true,test,new String[] {getString("save"),getString("abort")});
dlg.start();
if (dlg.getSelectedIndex() == 0)
{
String title = inputTitle.getText();
String firstname = inputFirstname.getText();
String surname =inputSurname.getText();
getUserModule().changeName(title,firstname,surname);
nameLabel.setText(user.getName());
}
}
catch (RaplaException ex)
{
showException( ex, getMainComponent());
}
}
}
class MyActionListener2 implements ActionListener {
JTextField emailField = new JTextField();
JTextField codeField = new JTextField();
RaplaButton sendCode = new RaplaButton();
RaplaButton validate = new RaplaButton();
public void actionPerformed(ActionEvent arg0) {
try
{
DialogUI dlg;
JPanel content = new JPanel();
GridLayout layout = new GridLayout();
layout.setColumns(3);
layout.setRows(2);
content.setLayout(layout);
content.add(new JLabel(getString("new_mail")));
content.add(emailField);
sendCode.setText(getString("send_code"));
content.add(sendCode);
sendCode.setAction(new EmailChangeActionB( emailField, codeField, validate));
content.add(new JLabel(getString("code_message3") + " "));
codeField.setEnabled(false);
content.add(codeField);
validate.setText(getString("code_validate"));
content.add(validate);
addCopyPaste(emailField);
addCopyPaste(codeField);
dlg = DialogUI.create(getContext(),getComponent(),true,content,new String[] {getString("save"),getString("abort")});
validate.setAction(new EmailChangeActionA(dlg));
validate.setEnabled(false);
dlg.setDefault(0);
dlg.setTitle("Email");
dlg.getButton(0).setAction(new EmailChangeActionC(getUserModule().getUser(), dlg));
dlg.getButton(0).setEnabled(false);
dlg.start();
}
catch (RaplaException ex)
{
showException( ex, getMainComponent());
}
}
class EmailChangeActionA extends AbstractAction {
private static final long serialVersionUID = 1L;
DialogUI dlg;
public EmailChangeActionA( DialogUI dlg){
this.dlg = dlg;
}
public void actionPerformed(ActionEvent arg0) {
try
{
User user = getUserModule().getUser();
boolean correct;
try {
int wert = Integer.parseInt(codeField.getText());
correct = wert == (Math.abs(user.getEmail().hashCode()));
} catch (NumberFormatException er)
{
correct = false;
}
if ( correct)
{
dlg.getButton(0).setEnabled(true);
}
else
{
JOptionPane.showMessageDialog(getMainComponent(),
getString("code_error1"),
getString("error"),
JOptionPane.ERROR_MESSAGE);
}
} catch (RaplaException ex) {
showException(ex, getMainComponent());
}
}
}
class EmailChangeActionB extends AbstractAction {
private static final long serialVersionUID = 1L;
JTextField rec;
JTextField code;
RaplaButton button;
public EmailChangeActionB(JTextField rec, JTextField code, RaplaButton button){
this.rec = rec;
this.button = button;
this.code = code;
}
public void actionPerformed(ActionEvent arg0)
{
try
{
String recepient = rec.getText();
getUserModule().confirmEmail(recepient);
button.setEnabled(true);
code.setEnabled(true);
}
catch (Exception ex) {
showException(ex, getMainComponent());
}
}
}
class EmailChangeActionC extends AbstractAction {
private static final long serialVersionUID = 1L;
User user;
DialogUI dlg;
public EmailChangeActionC(User user, DialogUI dlg){
this.user = user;
this.dlg = dlg;
}
public void actionPerformed(ActionEvent e) {
try {
String newMail = emailField.getText();
getUserModule().changeEmail(newMail);
emailLabel.setText(user.getEmail());
dlg.close();
} catch (RaplaException e1) {
e1.printStackTrace();
}
}
}
}
} | 04900db4-rob | src/org/rapla/gui/internal/UserOption.java | Java | gpl3 | 11,872 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.edit;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import org.rapla.entities.Category;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.EditField;
import org.rapla.gui.TreeFactory;
import org.rapla.gui.internal.edit.fields.AbstractEditField;
import org.rapla.gui.internal.edit.fields.BooleanField;
import org.rapla.gui.internal.edit.fields.GroupListField;
import org.rapla.gui.internal.edit.fields.TextField;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaTree;
/****************************************************************
* This is the controller-class for the User-Edit-Panel *
****************************************************************/
/*User
1. username, string
2. name,string
3. email,string,
4. isadmin,boolean
*/
class UserEditUI extends AbstractEditUI<User> {
TextField usernameField;
PersonSelectField personSelect;
TextField nameField;
TextField emailField;
AdminBooleanField adminField;
GroupListField groupField;
/**
* @param context
* @throws RaplaException
*/
public UserEditUI(RaplaContext context) throws RaplaException {
super(context);
List<EditField> fields = new ArrayList<EditField>();
usernameField = new TextField(context,getString("username"));
fields.add(usernameField);
personSelect = new PersonSelectField(context);
fields.add(personSelect);
nameField = new TextField(context,getString("name"));
fields.add(nameField);
emailField = new TextField(context,getString("email"));
fields.add(emailField);
adminField = new AdminBooleanField(context,getString("admin"),getUser());
fields.add(adminField);
groupField = new GroupListField(context);
fields.add(groupField);
setFields(fields);
}
class AdminBooleanField extends BooleanField implements ChangeListener {
User user;
public AdminBooleanField(RaplaContext sm, String fieldName, User user) {
super(sm, fieldName);
this.user = user;
}
public void stateChanged(ChangeEvent e) {
}
public void actionPerformed(ActionEvent evt) {
if(evt.getActionCommand().equals(getString("no"))) {
try {
if(!isOneAdmin())
{
showWarning(getString("error.no_admin"), getComponent());
setValue(true);
}
}
catch (RaplaException ex)
{
showException(ex, getComponent());
}
}
return;
}
private Boolean isOneAdmin() throws RaplaException {
User[] userList = getQuery().getUsers();
for (final User user: userList)
{
if(!user.equals(this.user) && user.isAdmin())
{
return true;
}
}
return false;
}
}
class PersonSelectField extends AbstractEditField implements ChangeListener, ActionListener {
User user;
JPanel panel = new JPanel();
JToolBar toolbar = new JToolBar();
RaplaButton newButton = new RaplaButton(RaplaButton.SMALL);
RaplaButton removeButton = new RaplaButton(RaplaButton.SMALL);
/**
* @param sm
* @throws RaplaException
*/
public PersonSelectField(RaplaContext sm) throws RaplaException {
super(sm);
setFieldName( getString("person"));
final Category rootCategory = getQuery().getUserGroupsCategory();
if ( rootCategory == null )
return;
toolbar.add( newButton );
toolbar.add( removeButton );
toolbar.setFloatable( false );
panel.setLayout( new BorderLayout() );
panel.add( toolbar, BorderLayout.NORTH );
newButton.addActionListener( this );
removeButton.addActionListener( this );
removeButton.setText( getString("remove") );
removeButton.setIcon( getIcon( "icon.remove" ) );
newButton.setText( getString("bind_with_person") );
newButton.setIcon( getIcon( "icon.new" ) );
}
private void updateButton() {
final boolean personSet = user != null && user.getPerson() != null;
removeButton.setEnabled( personSet) ;
newButton.setEnabled( !personSet) ;
nameField.getComponent().setEnabled( !personSet);
emailField.getComponent().setEnabled( !personSet);
}
public JComponent getComponent() {
return panel;
}
public String getName()
{
return getString("bind_with_person");
}
public void setUser(User o){
user = o;
updateButton();
}
public void actionPerformed(ActionEvent evt) {
if ( evt.getSource() == newButton)
{
try {
showAddDialog();
} catch (RaplaException ex) {
showException(ex,newButton);
}
}
if ( evt.getSource() == removeButton)
{
try {
user.setPerson( null );
user.setEmail( null );
user.setName(null);
nameField.setValue( user.getName());
emailField.setValue( user.getEmail());
updateButton();
} catch (RaplaException ex) {
showException(ex, getComponent());
}
}
}
public void stateChanged(ChangeEvent evt) {
}
private void showAddDialog() throws RaplaException {
final DialogUI dialog;
RaplaTree treeSelection = new RaplaTree();
treeSelection.setMultiSelect(true);
final TreeFactory treeFactory = getTreeFactory();
treeSelection.getTree().setCellRenderer(treeFactory.createRenderer());
final DynamicType[] personTypes = getQuery().getDynamicTypes(DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON);
List<ClassificationFilter> filters = new ArrayList<ClassificationFilter>();
for (DynamicType personType: personTypes)
{
if ( personType.getAttribute("email") != null)
{
final ClassificationFilter filter = personType.newClassificationFilter();
filters.add( filter);
}
}
final Allocatable[] allocatables = getQuery().getAllocatables(filters.toArray(ClassificationFilter.CLASSIFICATIONFILTER_ARRAY));
List<Allocatable> allocatablesWithEmail = new ArrayList<Allocatable>();
for ( Allocatable a: allocatables)
{
final Classification classification = a.getClassification();
final Attribute attribute = classification.getAttribute("email");
if ( attribute != null)
{
final String email = (String)classification.getValue(attribute);
if (email != null && email.length() > 0)
{
allocatablesWithEmail.add( a );
}
}
}
final Allocatable[] allocatableArray = allocatablesWithEmail.toArray(Allocatable.ALLOCATABLE_ARRAY);
treeSelection.exchangeTreeModel(treeFactory.createClassifiableModel(allocatableArray,true));
treeSelection.setMinimumSize(new java.awt.Dimension(300, 200));
treeSelection.setPreferredSize(new java.awt.Dimension(400, 260));
dialog = DialogUI.create(
getContext()
,getComponent()
,true
,treeSelection
,new String[] { getString("apply"),getString("cancel")});
final JTree tree = treeSelection.getTree();
tree.addMouseListener(new MouseAdapter() {
// End dialog when a leaf is double clicked
public void mousePressed(MouseEvent e) {
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
if (selPath != null && e.getClickCount() == 2) {
final Object lastPathComponent = selPath.getLastPathComponent();
if (((TreeNode) lastPathComponent).isLeaf() )
dialog.getButton(0).doClick();
}
else if (selPath != null && e.getClickCount() == 1) {
final Object lastPathComponent = selPath.getLastPathComponent();
if (((TreeNode) lastPathComponent).isLeaf() )
dialog.getButton(0).setEnabled(true);
else
dialog.getButton(0).setEnabled(false);
}
}
});
dialog.setTitle(getName());
dialog.start();
if (dialog.getSelectedIndex() == 0) {
Iterator<?> it = treeSelection.getSelectedElements().iterator();
while (it.hasNext()) {
user.setPerson((Allocatable) it.next());
nameField.setValue( user.getName());
emailField.setValue( user.getEmail());
updateButton();
}
}
}
}
final private TreeFactory getTreeFactory() {
return getService(TreeFactory.class);
}
@Override
public void mapToObjects() throws RaplaException {
if (objectList == null)
return;
if (objectList.size() == 1 )
{
User user = objectList.iterator().next();
user.setName(nameField.getValue());
user.setEmail( emailField.getValue());
user.setUsername( usernameField.getValue());
user.setAdmin( adminField.getValue());
// personselect stays in sync
}
groupField.mapTo( objectList);
}
// overwriting of the method by AbstractEditUI
// goal: deactivation of the username-field in case of processing multiple
// objects, to avoid that usernames (identifier) are processed at the same
// time
// => multiple users would have the same username
@Override
protected void mapFromObjects() throws RaplaException {
boolean multiedit = objectList.size() > 1;
if (objectList.size() == 1 )
{
User user = objectList.iterator().next();
nameField.setValue(user.getName());
emailField.setValue(user.getEmail());
usernameField.setValue(user.getUsername( ));
adminField.setValue( user.isAdmin( ));
personSelect.setUser( user);
}
groupField.mapFrom( objectList);
for (EditField field:fields) {
// deactivation of the all fields except group for multiple objects
if (multiedit && !(field instanceof GroupListField ))
{
field.getComponent().setEnabled(false);
field.getComponent().setVisible(false);
}
}
}
}
| 04900db4-rob | src/org/rapla/gui/internal/edit/UserEditUI.java | Java | gpl3 | 13,212 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.edit;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.ItemSelectable;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.util.Assert;
import org.rapla.entities.Category;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.ClassificationFilterRule;
import org.rapla.entities.dynamictype.ConstraintIds;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.facade.ClassifiableFilter;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.EditField;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.common.NamedListCellRenderer;
import org.rapla.gui.internal.edit.fields.AbstractEditField;
import org.rapla.gui.internal.edit.fields.AllocatableSelectField;
import org.rapla.gui.internal.edit.fields.BooleanField;
import org.rapla.gui.internal.edit.fields.CategoryListField;
import org.rapla.gui.internal.edit.fields.CategorySelectField;
import org.rapla.gui.internal.edit.fields.DateField;
import org.rapla.gui.internal.edit.fields.LongField;
import org.rapla.gui.internal.edit.fields.SetGetField;
import org.rapla.gui.internal.edit.fields.TextField;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaWidget;
public class ClassifiableFilterEdit extends RaplaGUIComponent
implements
ActionListener
,RaplaWidget
{
JPanel content = new JPanel();
JScrollPane scrollPane;
JCheckBox[] checkBoxes;
ClassificationEdit[] filterEdit;
DynamicType[] types;
boolean isResourceSelection;
ArrayList<ChangeListener> listenerList = new ArrayList<ChangeListener>();
final RaplaButton everythingButton = new RaplaButton(RaplaButton.SMALL);
final RaplaButton nothingButton = new RaplaButton(RaplaButton.SMALL);
public ClassifiableFilterEdit(RaplaContext context, boolean isResourceSelection) {
super( context);
content.setBackground(UIManager.getColor("List.background"));
scrollPane = new JScrollPane(content
,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS
,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED
);
scrollPane.setPreferredSize(new Dimension(590,400));
this.isResourceSelection = isResourceSelection;
content.setBorder( BorderFactory.createEmptyBorder(5,5,5,5));
everythingButton.setText( getString("select_everything") );
everythingButton.setIcon( getIcon("icon.all-checked"));
nothingButton.setText(getString("select_nothing"));
nothingButton.setIcon( getIcon("icon.all-unchecked"));
}
public JComponent getClassificationTitle(String classificationType) {
JLabel title = new JLabel( classificationType );
title.setFont( title.getFont().deriveFont( Font.BOLD ));
title.setText( getString( classificationType) + ":" );
return title;
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(listener);
}
public void removeChangeListener(ChangeListener listener) {
listenerList.remove(listener);
}
public ChangeListener[] getChangeListeners() {
return listenerList.toArray(new ChangeListener[]{});
}
protected void fireFilterChanged() {
if (listenerList.size() == 0)
return;
ChangeEvent evt = new ChangeEvent(this);
ChangeListener[] listeners = getChangeListeners();
for (int i = 0;i<listeners.length; i++) {
listeners[i].stateChanged(evt);
}
everythingButton.setEnabled( true);
nothingButton.setEnabled( true);
}
public void setTypes(DynamicType[] types) {
this.types = types;
content.removeAll();
TableLayout tableLayout = new TableLayout();
content.setLayout(tableLayout);
tableLayout.insertColumn(0,TableLayout.PREFERRED);
tableLayout.insertColumn(1,10);
tableLayout.insertColumn(2,TableLayout.FILL);
tableLayout.insertRow(0, TableLayout.PREFERRED);
if (checkBoxes != null) {
for (int i=0;i<checkBoxes.length;i++) {
checkBoxes[i].removeActionListener(this);
}
}
int defaultRowSize = 35;
scrollPane.setPreferredSize(new Dimension(590,Math.max(200,Math.min(600, 70+ defaultRowSize + types.length * 33 + (isResourceSelection ? 20:0)))));
checkBoxes = new JCheckBox[types.length];
filterEdit = new ClassificationEdit[types.length];
String lastClassificationType= null;
int row = 0;
for (int i=0;i<types.length;i++) {
String classificationType = types[i].getAnnotation( DynamicTypeAnnotations.KEY_CLASSIFICATION_TYPE);
if ( !classificationType.equals( lastClassificationType)) {
tableLayout.insertRow( row, 2);
row ++;
lastClassificationType = classificationType;
tableLayout.insertRow( row, TableLayout.MINIMUM);
content.add( getClassificationTitle( classificationType),"0,"+ row +",1," + row) ;
if ( i== 0 )
{
everythingButton.setSelected( true);
ActionListener resetButtonListener = new ActionListener() {
private boolean enabled = true;
public void actionPerformed(ActionEvent evt) {
try
{
if ( !enabled)
{
return;
}
enabled = false;
JButton source = (JButton)evt.getSource();
boolean isEverything = source == everythingButton;
source.setSelected( isEverything ? true : false);
boolean deselectAllIfFilterIsNull = !isEverything;
mapFromIntern( null, deselectAllIfFilterIsNull);
fireFilterChanged();
source.setEnabled( false);
JButton opposite = isEverything ? nothingButton : everythingButton;
opposite.setEnabled( true);
}
catch (RaplaException ex)
{
showException(ex, getComponent());
}
finally
{
enabled = true;
}
}
};
everythingButton.addActionListener( resetButtonListener);
nothingButton.addActionListener( resetButtonListener);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground( content.getBackground());
buttonPanel.add( everythingButton);
buttonPanel.add( nothingButton);
content.add( buttonPanel,"2,"+ row +",r,c");
}
row ++;
tableLayout.insertRow( row, 4);
row ++;
tableLayout.insertRow( row, 2);
content.add( new JPanel() , "0," + row + ",2," + row );
row ++;
}
tableLayout.insertRow( row, 3);
tableLayout.insertRow( row + 1, TableLayout.MINIMUM);
tableLayout.insertRow( row + 2, TableLayout.MINIMUM);
tableLayout.insertRow( row + 3, 3);
tableLayout.insertRow( row + 4, 2);
checkBoxes[i] = new JCheckBox(getName(types[i]));
final JCheckBox checkBox = checkBoxes[i];
checkBox.setBorder( BorderFactory.createEmptyBorder(0,10,0,0));
checkBox.setOpaque( false );
checkBox.addActionListener(this);
checkBox.setSelected( true );
content.add( checkBox , "0," + (row + 1) + ",l,t");
filterEdit[i] = new ClassificationEdit(getContext(), scrollPane);
final ClassificationEdit edit = filterEdit[i];
content.add( edit.getNewComponent() , "2," + (row + 1));
content.add( edit.getRulesComponent() , "0," + (row + 2) + ",2,"+ (row + 2));
content.add( new JPanel() , "0," + (row + 4) + ",2," + (row + 4));
edit.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
everythingButton.setEnabled( true);
nothingButton.setEnabled( true);
fireFilterChanged();
}
}
);
row += 5;
}
}
private ClassificationFilter findFilter(DynamicType type,ClassificationFilter[] filters) {
for (int i=0;i<filters.length;i++)
if (filters[i].getType().equals(type))
return filters[i];
return null;
}
public void setFilter(ClassifiableFilter filter) throws RaplaException {
List<DynamicType> list = new ArrayList<DynamicType>();
if ( !isResourceSelection) {
list.addAll( Arrays.asList( getQuery().getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESERVATION )));
}
else
{
list.addAll( Arrays.asList( getQuery().getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_RESOURCE )));
list.addAll( Arrays.asList( getQuery().getDynamicTypes( DynamicTypeAnnotations.VALUE_CLASSIFICATION_TYPE_PERSON )));
}
setTypes( list.toArray( DynamicType.DYNAMICTYPE_ARRAY));
mapFromIntern(filter, false);
}
private void mapFromIntern(ClassifiableFilter classifiableFilter, boolean deselectAllIfFilterIsNull) throws RaplaException {
final ClassificationFilter[] filters;
if ( classifiableFilter != null)
{
filters = isResourceSelection ? classifiableFilter.getAllocatableFilter() : classifiableFilter.getReservationFilter();
}
else
{
filters = new ClassificationFilter[] {};
}
boolean nothingSelectable = false;
for (int i=0;i<types.length;i++) {
final DynamicType dynamicType = types[i];
ClassificationFilter filter = findFilter(dynamicType, filters);
final boolean fillDefault;
if ( classifiableFilter != null)
{
fillDefault = isResourceSelection ? classifiableFilter.isDefaultResourceTypes() : classifiableFilter.isDefaultEventTypes();
}
else
{
fillDefault = !deselectAllIfFilterIsNull;
}
if ( filter == null && fillDefault)
{
filter = dynamicType.newClassificationFilter();
}
checkBoxes[i].setSelected( filter != null);
if ( filter != null)
{
nothingSelectable = true;
}
filterEdit[i].mapFrom(filter);
}
if ( classifiableFilter != null)
{
everythingButton.setEnabled( ! (isResourceSelection ? classifiableFilter.isDefaultResourceTypes() :classifiableFilter.isDefaultEventTypes()));
}
nothingButton.setEnabled( nothingSelectable);
scrollPane.revalidate();
scrollPane.repaint();
}
public ClassificationFilter[] getFilters() {
ArrayList<ClassificationFilter> list = new ArrayList<ClassificationFilter>();
for (int i=0; i< filterEdit.length; i++) {
ClassificationFilter filter = filterEdit[i].getFilter();
if (filter != null) {
list.add(filter);
}
}
return list.toArray(new ClassificationFilter[] {});
}
public void actionPerformed(ActionEvent evt) {
for (int i=0;i<checkBoxes.length;i++) {
if (checkBoxes[i] == evt.getSource()) {
if (checkBoxes[i].isSelected())
filterEdit[i].mapFrom(types[i].newClassificationFilter());
else
filterEdit[i].mapFrom(null);
// activate the i. filter
}
}
content.revalidate();
content.repaint();
fireFilterChanged();
everythingButton.setEnabled( true);
nothingButton.setEnabled( true);
}
public JComponent getComponent() {
return scrollPane;
}
}
class ClassificationEdit extends RaplaGUIComponent implements ItemListener {
JPanel ruleListPanel = new JPanel();
JPanel newPanel = new JPanel();
List<RuleComponent> ruleList = new ArrayList<RuleComponent>();
JComboBox attributeSelector;
JButton newLabel = new JButton();
DynamicType type;
ArrayList<ChangeListener> listenerList = new ArrayList<ChangeListener>();
JScrollPane pane;
ClassificationEdit(RaplaContext sm,JScrollPane pane){
super(sm );
this.pane = pane;
ruleListPanel.setOpaque( false );
ruleListPanel.setLayout(new BoxLayout(ruleListPanel,BoxLayout.Y_AXIS));
newPanel.setOpaque( false );
newPanel.setLayout(new TableLayout(new double[][] {{TableLayout.PREFERRED},{TableLayout.PREFERRED}}));
}
public void addChangeListener(ChangeListener listener) {
listenerList.add(listener);
}
public void removeChangeListener(ChangeListener listener) {
listenerList.remove(listener);
}
public ChangeListener[] getChangeListeners() {
return listenerList.toArray(new ChangeListener[]{});
}
protected void fireFilterChanged() {
if (listenerList.size() == 0)
return;
ChangeEvent evt = new ChangeEvent(this);
ChangeListener[] listeners = getChangeListeners();
for (int i = 0;i<listeners.length; i++) {
listeners[i].stateChanged(evt);
}
}
public JComponent getRulesComponent() {
return ruleListPanel;
}
public JComponent getNewComponent() {
return newPanel;
}
@SuppressWarnings("unchecked")
public void mapFrom(ClassificationFilter filter) {
getRulesComponent().removeAll();
ruleList.clear();
getNewComponent().removeAll();
if ( filter == null) {
type = null;
return;
}
this.type = filter.getType();
Attribute[] attributes = type.getAttributes();
if (attributes.length == 0 )
return;
if (attributeSelector != null)
attributeSelector.removeItemListener(this);
JComboBox jComboBox = new JComboBox(attributes);
attributeSelector = jComboBox;
attributeSelector.setRenderer(new NamedListCellRenderer(getI18n().getLocale()) {
private static final long serialVersionUID = 1L;
public Component getListCellRendererComponent(JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
if (value == null) {
setText(getString("new_rule"));
return this;
} else {
return super.getListCellRendererComponent(list, value,index,isSelected,cellHasFocus);
}
}
});
attributeSelector.addItemListener(this);
newPanel.add(newLabel,"0,0,f,c");
newPanel.add(attributeSelector,"0,0,f,c");
newLabel.setText(getString("new_rule"));
newLabel.setVisible(false);
attributeSelector.setSelectedItem(null);
Iterator<? extends ClassificationFilterRule> it = filter.ruleIterator();
while (it.hasNext()) {
ClassificationFilterRule rule = it.next();
RuleComponent ruleComponent = new RuleComponent( rule);
ruleList.add( ruleComponent );
}
update();
}
public void update() {
ruleListPanel.removeAll();
int i=0;
for (Iterator<RuleComponent> it = ruleList.iterator();it.hasNext();) {
RuleComponent rule = it.next();
ruleListPanel.add( rule);
rule.setAndVisible( i > 0);
i++;
}
ruleListPanel.revalidate();
ruleListPanel.repaint();
}
public void itemStateChanged(ItemEvent e) {
Object item = e.getItem();
if ( e.getStateChange() != ItemEvent.SELECTED)
{
return;
}
Attribute att = (Attribute)item;
if (att != null) {
RuleComponent ruleComponent = getComponent(att);
final RuleRow row;
if (ruleComponent == null) {
ruleComponent = new RuleComponent( att);
ruleList.add( ruleComponent );
}
row = ruleComponent.addOr();
final RuleComponent comp = ruleComponent;
update();
// invokeLater prevents a deadlock in jdk <=1.3
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
attributeSelector.setSelectedIndex(-1);
comp.scrollRowVisible(row);
}
});
fireFilterChanged();
}
}
public ClassificationFilter getFilter() {
if ( type == null )
return null;
ClassificationFilter filter = type.newClassificationFilter();
int i=0;
for (Iterator<RuleComponent> it = ruleList.iterator();it.hasNext();) {
RuleComponent ruleComponent = it.next();
Attribute attribute = ruleComponent.getAttribute();
List<RuleRow> ruleRows = ruleComponent.getRuleRows();
int size = ruleRows.size();
Object[][] conditions = new Object[size][2];
for (int j=0;j<size;j++) {
RuleRow ruleRow = ruleRows.get(j);
conditions[j][0] = ruleRow.getOperatorValue();
conditions[j][1] = ruleRow.getValue();
}
filter.setRule(i++ , attribute, conditions);
}
return filter;
}
private RuleComponent getComponent(Attribute attribute) {
for (Iterator<RuleComponent> it = ruleList.iterator();it.hasNext();) {
RuleComponent c2 = it.next();
if (attribute.equals(c2.getAttribute())) {
return c2;
}
}
return null;
}
private void deleteRule(Component ruleComponent) {
ruleList.remove( ruleComponent );
update();
}
class RuleComponent extends JPanel {
private static final long serialVersionUID = 1L;
Attribute attribute;
private final Listener listener = new Listener();
List<RuleRow> ruleRows = new ArrayList<RuleRow>();
List<RaplaButton> deleteButtons = new ArrayList<RaplaButton>();
boolean isAndVisible;
JLabel and;
RuleComponent(Attribute attribute) {
Border outer = BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(5,20,0,3)
,BorderFactory.createEtchedBorder()
);
this.setBorder(BorderFactory.createCompoundBorder(
outer
,BorderFactory.createEmptyBorder(2,3,2,3)
));
this.setOpaque( false );
this.attribute = attribute;
}
RuleComponent(ClassificationFilterRule rule){
this( rule.getAttribute());
Assert.notNull(attribute);
Object[] ruleValues = rule.getValues();
String[] operators = rule.getOperators();
for (int i=0;i<ruleValues.length;i++) {
RuleRow row = createRow(operators[i], ruleValues[i]);
ruleRows.add(row);
}
rebuild();
}
public Attribute getAttribute() {
return attribute;
}
public List<RuleRow> getRuleRows() {
return ruleRows;
}
private RuleRow addOr() {
RuleRow row = createRow(null,null);
ruleRows.add(row);
rebuild();
return row;
}
protected void scrollRowVisible(RuleRow row) {
Component ruleComponent = row.ruleLabel;
if ( ruleComponent == null || ruleComponent.getParent() == null)
{
ruleComponent = row.field.getComponent();
}
if ( ruleComponent != null)
{
Point location1 = ruleComponent.getLocation();
Point location2 = getLocation();
Point location3 = ruleListPanel.getLocation();
int y = location1.y + location2.y + location3.y ;
int height2 = (int)ruleComponent.getPreferredSize().getHeight()+20;
Rectangle aRect = new Rectangle(location1.x,y , 10, height2);
JViewport viewport = pane.getViewport();
viewport.scrollRectToVisible( aRect);
}
}
public void setAndVisible( boolean andVisible) {
this.isAndVisible = andVisible;
if ( and!= null)
{
if ( andVisible) {
and.setText( getString("and"));
} else {
and.setText("");
}
}
}
private void rebuild() {
this.removeAll();
TableLayout layout = new TableLayout();
layout.insertColumn(0,TableLayout.PREFERRED);
layout.insertColumn(1,10);
layout.insertColumn(2,TableLayout.PREFERRED);
layout.insertColumn(3,5);
layout.insertColumn(4,TableLayout.PREFERRED);
layout.insertColumn(5,5);
layout.insertColumn(6,TableLayout.FILL);
this.setLayout(layout);
int row =0;
layout.insertRow(row,TableLayout.PREFERRED);
and = new JLabel();
// and.setAlignmentX( and.LEFT_ALIGNMENT);
this.add("0,"+row +",6,"+ row + ",l,c", and);
if ( isAndVisible) {
and.setText( getString("and"));
} else {
and.setText("");
}
row ++;
int size = ruleRows.size();
for (int i=0;i<size;i++) {
RuleRow ruleRow = ruleRows.get(i);
RaplaButton deleteButton = deleteButtons.get(i);
layout.insertRow(row,TableLayout.PREFERRED);
this.add("0," + row + ",l,c", deleteButton);
if (i == 0)
this.add("2," + row + ",l,c", ruleRow.ruleLabel);
else
this.add("2," + row + ",r,c", new JLabel(getString("or")));
this.add("4," + row + ",l,c", ruleRow.operatorComponent);
this.add("6," + row + ",f,c", ruleRow.field.getComponent());
row ++;
if (i<size -1) {
layout.insertRow(row , 2);
row++;
}
}
revalidate();
repaint();
}
private RuleRow createRow(String operator,Object ruleValue) {
RaplaButton deleteButton = new RaplaButton(RaplaButton.SMALL);
deleteButton.setToolTipText(getString("delete"));
deleteButton.setIcon(getIcon("icon.delete"));
deleteButton.addActionListener(listener);
deleteButtons.add(deleteButton);
RuleRow row = new RuleRow(attribute,operator,ruleValue);
return row;
}
class Listener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
int index = deleteButtons.indexOf(evt.getSource());
if (ruleRows.size() <= 1) {
deleteRule(RuleComponent.this);
} else {
ruleRows.remove(index);
deleteButtons.remove(index);
rebuild();
}
fireFilterChanged();
}
}
}
class RuleRow implements ChangeListener, ItemListener{
Object ruleValue;
JLabel ruleLabel;
JComponent operatorComponent;
AbstractEditField field;
Attribute attribute;
public void stateChanged(ChangeEvent e) {
fireFilterChanged();
}
public void itemStateChanged(ItemEvent e) {
fireFilterChanged();
}
RuleRow(Attribute attribute,String operator,Object ruleValue) {
this.attribute = attribute;
this.ruleValue = ruleValue;
ruleLabel = new JLabel();
ruleLabel.setText(attribute.getName().getName(getI18n().getLang()));
createField( attribute );
// we can cast here, because we tested in createField
@SuppressWarnings("unchecked")
SetGetField<Object> setGetField = (SetGetField<Object>)field;
setGetField.setValue(ruleValue);
field.addChangeListener( this);
setOperatorValue(operator);
if ( operatorComponent instanceof ItemSelectable)
{
((ItemSelectable)operatorComponent).addItemListener(this);
}
}
public String getOperatorValue() {
AttributeType type = attribute.getType();
if (type.equals(AttributeType.ALLOCATABLE) || type.equals(AttributeType.CATEGORY) || type.equals(AttributeType.BOOLEAN) )
return "is";
if (type.equals(AttributeType.STRING)) {
int index = ((JComboBox)operatorComponent).getSelectedIndex();
if (index == 0)
return "contains";
if (index == 1)
return "starts";
}
if (type.equals(AttributeType.DATE) || type.equals(AttributeType.INT)) {
int index = ((JComboBox)operatorComponent).getSelectedIndex();
if (index == 0)
return "<";
if (index == 1)
return "=";
if (index == 2)
return ">";
if (index == 3)
return "<>";
if (index == 4)
return "<=";
if (index == 5)
return ">=";
}
Assert.notNull(field,"Unknown AttributeType" + type);
return null;
}
private void setOperatorValue(String operator) {
AttributeType type = attribute.getType();
if ((type.equals(AttributeType.DATE) || type.equals(AttributeType.INT)))
{
if (operator == null)
operator = "<";
JComboBox box = (JComboBox)operatorComponent;
if (operator.equals("<"))
box.setSelectedIndex(0);
if (operator.equals("=") || operator.equals("is"))
box.setSelectedIndex(1);
if (operator.equals(">"))
box.setSelectedIndex(2);
if (operator.equals("<>"))
box.setSelectedIndex(3);
if (operator.equals("<="))
box.setSelectedIndex(4);
if (operator.equals(">="))
box.setSelectedIndex(5);
}
}
private EditField createField(Attribute attribute) {
operatorComponent = null;
AttributeType type = attribute.getType();
// used for static testing of the field type
@SuppressWarnings("unused")
SetGetField test;
RaplaContext context = getContext();
if (type.equals(AttributeType.ALLOCATABLE))
{
operatorComponent = new JLabel("");
DynamicType dynamicTypeConstraint = (DynamicType)attribute.getConstraint( ConstraintIds.KEY_DYNAMIC_TYPE);
AllocatableSelectField newField = new AllocatableSelectField(context, dynamicTypeConstraint);
field = newField;
test = newField;
}
else if (type.equals(AttributeType.CATEGORY))
{
operatorComponent = new JLabel("");
Category rootCategory = (Category)attribute.getConstraint(ConstraintIds.KEY_ROOT_CATEGORY);
if (rootCategory.getDepth() > 2) {
Category defaultCategory = (Category) attribute.defaultValue();
CategorySelectField newField = new CategorySelectField(context,rootCategory,defaultCategory);
field = newField;
test = newField;
} else {
CategoryListField newField = new CategoryListField(context,rootCategory);
field = newField;
test = newField;
}
}
else if (type.equals(AttributeType.STRING))
{
TextField newField = new TextField(context);
field = newField;
test = newField;
@SuppressWarnings("unchecked")
DefaultComboBoxModel model = new DefaultComboBoxModel(new String[] {
getString("filter.contains")
,getString("filter.starts")
});
@SuppressWarnings("unchecked")
JComboBox jComboBox = new JComboBox(model);
operatorComponent = jComboBox;
}
else if (type.equals(AttributeType.INT))
{
LongField newField = new LongField(context);
field = newField;
test = newField;
@SuppressWarnings("unchecked")
DefaultComboBoxModel model = new DefaultComboBoxModel(new String[] {
getString("filter.is_smaller_than")
,getString("filter.equals")
,getString("filter.is_greater_than")
,getString("filter.not_equals")
,getString("filter.smaller_or_equals")
,getString("filter.greater_or_equals")
});
@SuppressWarnings("unchecked")
JComboBox jComboBox = new JComboBox(model);
operatorComponent = jComboBox;
}
else if (type.equals(AttributeType.DATE))
{
DateField newField = new DateField(context);
field = newField;
test = newField;
@SuppressWarnings("unchecked")
DefaultComboBoxModel model = new DefaultComboBoxModel(new String[] {
getString("filter.earlier_than")
,getString("filter.equals")
,getString("filter.later_than")
,getString("filter.not_equals")
});
@SuppressWarnings("unchecked")
JComboBox jComboBox = new JComboBox(model);
operatorComponent = jComboBox; }
else if (type.equals(AttributeType.BOOLEAN))
{
operatorComponent = new JLabel("");
BooleanField newField = new BooleanField(context);
field = newField;
test = newField;
ruleValue = new Boolean(false);
}
Assert.notNull(field,"Unknown AttributeType");
return field;
}
public Object getValue() {
ruleValue = ((SetGetField<?>)field).getValue();
return ruleValue;
}
}
}
| 04900db4-rob | src/org/rapla/gui/internal/edit/ClassifiableFilterEdit.java | Java | gpl3 | 34,412 |
package org.rapla.gui.internal.edit.annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.rapla.entities.Annotatable;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.AnnotationEditExtension;
import org.rapla.gui.EditField;
import org.rapla.gui.internal.edit.AbstractEditUI;
public class AnnotationEditUI extends AbstractEditUI<Annotatable>
{
Collection<AnnotationEditExtension> annotationExtensions;
Map<AnnotationEditExtension,EditField> fieldMap = new HashMap<AnnotationEditExtension,EditField>();
public AnnotationEditUI(RaplaContext context, Collection<AnnotationEditExtension> annotationExtensions) {
super(context);
this.annotationExtensions = annotationExtensions;
}
@Override
public void mapToObjects() throws RaplaException {
}
@Override
protected void mapFromObjects() throws RaplaException {
List<EditField> fields = new ArrayList<EditField>();
Annotatable annotatable = objectList.get(0);
for ( AnnotationEditExtension annot: annotationExtensions)
{
EditField field = annot.createEditField(annotatable);
if ( field != null)
{
fields.add( field);
fieldMap.put( annot, field);
}
}
setFields(fields);
}
public void mapTo(List<Annotatable> annotatables) throws RaplaException {
Annotatable annotatable = annotatables.get(0);
for ( AnnotationEditExtension annot: annotationExtensions)
{
EditField field = fieldMap.get( annot);
annot.mapTo(field, annotatable);
}
}
}
| 04900db4-rob | src/org/rapla/gui/internal/edit/annotation/AnnotationEditUI.java | Java | gpl3 | 1,798 |
package org.rapla.gui.internal.edit.annotation;
import org.rapla.entities.Annotatable;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeAnnotations;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.AnnotationEditExtension;
import org.rapla.gui.EditField;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.edit.fields.BooleanField;
public class ColorAnnotationEdit extends RaplaGUIComponent implements AnnotationEditExtension{
private final String annotationName = AttributeAnnotations.KEY_COLOR;
public ColorAnnotationEdit(RaplaContext context) {
super(context);
}
@Override
public EditField createEditField(Annotatable annotatable) {
if (!( annotatable instanceof Attribute))
{
return null;
}
Attribute attribute = (Attribute)annotatable;
AttributeType type = attribute.getType();
if ( type!=AttributeType.CATEGORY && type!= AttributeType.STRING)
{
return null;
}
String annotation = annotatable.getAnnotation(annotationName);
BooleanField field = new BooleanField(getContext(),getString("color"));
if ( annotation != null)
{
field.setValue( annotation.equalsIgnoreCase("true"));
}
return field;
}
@Override
public void mapTo(EditField field, Annotatable annotatable) throws RaplaException
{
if ( field != null)
{
Boolean value = ((BooleanField)field).getValue();
if ( value != null && value == true)
{
annotatable.setAnnotation(annotationName, Boolean.TRUE.toString());
return;
}
}
annotatable.setAnnotation(annotationName, null);
}
}
| 04900db4-rob | src/org/rapla/gui/internal/edit/annotation/ColorAnnotationEdit.java | Java | gpl3 | 1,929 |
package org.rapla.gui.internal.edit.annotation;
import org.rapla.entities.Annotatable;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeAnnotations;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.AnnotationEditExtension;
import org.rapla.gui.EditField;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.edit.fields.LongField;
public class ExpectedRowsAnnotationEdit extends RaplaGUIComponent implements AnnotationEditExtension {
protected String annotationName = AttributeAnnotations.KEY_EXPECTED_ROWS;
protected Long DEFAULT_VALUE = new Long(1);
protected String fieldName = "expected_rows";
public ExpectedRowsAnnotationEdit(RaplaContext context) {
super(context);
}
@Override
public EditField createEditField(Annotatable annotatable) {
if (!( annotatable instanceof Attribute))
{
return null;
}
Attribute attribute = (Attribute)annotatable;
AttributeType type = attribute.getType();
if ( type!=AttributeType.STRING)
{
return null;
}
String annotation = annotatable.getAnnotation(annotationName);
LongField field = new LongField(getContext(),fieldName);
if ( annotation != null)
{
field.setValue( Integer.parseInt(annotation));
}
else
{
field.setValue( DEFAULT_VALUE);
}
addCopyPaste(field.getComponent());
return field;
}
@Override
public void mapTo(EditField field, Annotatable annotatable) throws RaplaException {
if ( field != null)
{
Long value = ((LongField)field).getValue();
if ( value != null && !value.equals(DEFAULT_VALUE))
{
annotatable.setAnnotation(annotationName, value.toString());
return;
}
}
annotatable.setAnnotation(annotationName, null);
}
}
| 04900db4-rob | src/org/rapla/gui/internal/edit/annotation/ExpectedRowsAnnotationEdit.java | Java | gpl3 | 2,118 |
package org.rapla.gui.internal.edit.annotation;
import org.rapla.entities.Annotatable;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeAnnotations;
import org.rapla.entities.dynamictype.AttributeType;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.AnnotationEditExtension;
import org.rapla.gui.EditField;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.edit.fields.BooleanField;
public class EmailAnnotationEdit extends RaplaGUIComponent implements AnnotationEditExtension{
private final String annotationName = AttributeAnnotations.KEY_EMAIL;
public EmailAnnotationEdit(RaplaContext context) {
super(context);
}
@Override
public EditField createEditField(Annotatable annotatable) {
if (!( annotatable instanceof Attribute))
{
return null;
}
Attribute attribute = (Attribute)annotatable;
AttributeType type = attribute.getType();
if (type!= AttributeType.STRING)
{
return null;
}
String annotation = annotatable.getAnnotation(annotationName);
BooleanField field = new BooleanField(getContext(),getString("email"));
if ( annotation != null )
{
field.setValue( annotation.equalsIgnoreCase("true"));
}
else
{
if ( attribute.getKey().equalsIgnoreCase("email"))
{
field.setValue( true );
}
}
return field;
}
@Override
public void mapTo(EditField field, Annotatable annotatable) throws RaplaException
{
if ( field != null)
{
Boolean value = ((BooleanField)field).getValue();
if ( value != null )
{
if ( value )
{
annotatable.setAnnotation(annotationName, Boolean.TRUE.toString());
return;
}
else if (( (Attribute)annotatable).getKey().equals("email"))
{
annotatable.setAnnotation(annotationName, Boolean.FALSE.toString());
}
}
}
annotatable.setAnnotation(annotationName, null);
}
}
| 04900db4-rob | src/org/rapla/gui/internal/edit/annotation/EmailAnnotationEdit.java | Java | gpl3 | 2,320 |
package org.rapla.gui.internal.edit.annotation;
import org.rapla.entities.dynamictype.AttributeAnnotations;
import org.rapla.framework.RaplaContext;
import org.rapla.gui.AnnotationEditExtension;
import org.rapla.gui.internal.edit.fields.TextField;
public class ExpectedColumnsAnnotationEdit extends ExpectedRowsAnnotationEdit implements AnnotationEditExtension {
public ExpectedColumnsAnnotationEdit(RaplaContext context) {
super(context);
fieldName="expected_columns";
annotationName = AttributeAnnotations.KEY_EXPECTED_COLUMNS;
DEFAULT_VALUE = new Long(TextField.DEFAULT_LENGTH);
}
}
| 04900db4-rob | src/org/rapla/gui/internal/edit/annotation/ExpectedColumnsAnnotationEdit.java | Java | gpl3 | 635 |
package org.rapla.gui.internal.edit.annotation;
import org.rapla.entities.Annotatable;
import org.rapla.entities.dynamictype.Attribute;
import org.rapla.entities.dynamictype.AttributeAnnotations;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.AnnotationEditExtension;
import org.rapla.gui.EditField;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.internal.edit.fields.BooleanField;
public class CategorizationAnnotationEdit extends RaplaGUIComponent implements AnnotationEditExtension{
final String annotationName = AttributeAnnotations.KEY_CATEGORIZATION;
public CategorizationAnnotationEdit(RaplaContext context) {
super(context);
}
@Override
public EditField createEditField(Annotatable annotatable) {
if (!( annotatable instanceof Attribute))
{
return null;
}
Attribute attribute = (Attribute)annotatable;
String annotation = annotatable.getAnnotation(annotationName);
BooleanField field = new BooleanField(getContext(),getString("categorization"));
if ( annotation != null)
{
field.setValue( annotation.equalsIgnoreCase("true"));
}
else
{
if ( attribute.getKey().equalsIgnoreCase("categorization"))
{
field.setValue( true );
}
}
return field;
}
@Override
public void mapTo(EditField field, Annotatable annotatable) throws RaplaException
{
if ( field != null)
{
Boolean value = ((BooleanField)field).getValue();
if ( value != null )
{
if ( value)
{
annotatable.setAnnotation(annotationName, Boolean.TRUE.toString());
return;
}
else if (( (Attribute)annotatable).getKey().equals("categorization"))
{
annotatable.setAnnotation(annotationName, Boolean.FALSE.toString());
return;
}
}
}
annotatable.setAnnotation(annotationName, null);
}
}
| 04900db4-rob | src/org/rapla/gui/internal/edit/annotation/CategorizationAnnotationEdit.java | Java | gpl3 | 2,204 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.edit;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import org.rapla.components.calendar.RaplaArrowButton;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.util.Tools;
import org.rapla.entities.Category;
import org.rapla.entities.CategoryAnnotations;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.EditComponent;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.TreeFactory;
import org.rapla.gui.internal.edit.fields.MultiLanguageField;
import org.rapla.gui.internal.edit.fields.TextField;
import org.rapla.gui.internal.view.TreeFactoryImpl.NamedNode;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaTree;
/**
* @author Christopher Kohlhaas
*/
public class CategoryEditUI extends RaplaGUIComponent
implements
EditComponent<Category>
{
JPanel panel = new JPanel();
JPanel toolbar = new JPanel();
RaplaButton newButton = new RaplaButton();
RaplaButton newSubButton = new RaplaButton();
RaplaButton removeButton = new RaplaButton();
RaplaArrowButton moveUpButton = new RaplaArrowButton('^', 25);
RaplaArrowButton moveDownButton = new RaplaArrowButton('v', 25);
Category rootCategory;
CategoryDetail detailPanel;
RaplaTreeEdit treeEdit;
TreeModel model;
boolean editKeys = true;
Listener listener = new Listener();
TreeCellRenderer iconRenderer;
boolean createNew;
public CategoryEditUI(RaplaContext context, boolean createNew) {
super( context);
this.createNew = createNew;
detailPanel = new CategoryDetail(context);
panel.setPreferredSize( new Dimension( 690,350 ) );
treeEdit = new RaplaTreeEdit( getI18n(),detailPanel.getComponent(), listener );
treeEdit.setListDimension( new Dimension( 250,100 ) );
toolbar.setLayout( new BoxLayout(toolbar, BoxLayout.X_AXIS));
toolbar.add(newButton);
toolbar.add(newSubButton);
toolbar.add( Box.createHorizontalStrut( 5 ));
toolbar.add(removeButton);
toolbar.add( Box.createHorizontalStrut( 5 ));
toolbar.add(moveUpButton);
toolbar.add(moveDownButton);
panel.setLayout( new BorderLayout() );
panel.add( toolbar, BorderLayout.NORTH );
panel.add( treeEdit.getComponent(), BorderLayout.CENTER );
newButton.addActionListener(listener);
newSubButton.addActionListener(listener);
removeButton.addActionListener(listener);
moveUpButton.addActionListener( listener );
moveDownButton.addActionListener( listener );
iconRenderer = getTreeFactory().createRenderer();
treeEdit.getTree().setCellRenderer( new TreeCellRenderer() {
public Component getTreeCellRendererComponent(JTree tree
,Object value
,boolean sel
,boolean expanded
,boolean leaf
,int row
,boolean hasFocus
) {
if ( value instanceof NamedNode) {
Category c = (Category) ((NamedNode)value).getUserObject();
value = c.getName(getRaplaLocale().getLocale());
if (editKeys) {
value = "{" + c.getKey() + "} " + value;
}
}
return iconRenderer.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus );
}
});
newButton.setText( getString("new_category") );
newButton.setIcon( getIcon("icon.new"));
newSubButton.setText( getString("new_sub-category") );
newSubButton.setIcon( getIcon("icon.new") );
removeButton.setText( getString("delete") );
removeButton.setIcon( getIcon("icon.delete") );
detailPanel.addChangeListener( listener );
detailPanel.setEditKeys( editKeys );
}
final private TreeFactory getTreeFactory() {
return getService(TreeFactory.class);
}
class Listener implements ActionListener,ChangeListener {
public void actionPerformed(ActionEvent evt) {
try {
if ( evt.getSource() == newButton ) {
createCategory( false );
} else if ( evt.getSource() == newSubButton ) {
createCategory( true );
} else if ( evt.getSource() == removeButton ) {
removeCategory();
} else if ( evt.getSource() == moveUpButton ) {
moveCategory( -1);
} else if ( evt.getSource() == moveDownButton ) {
moveCategory( 1);
} else if (evt.getActionCommand().equals("edit")) {
Category category = (Category) treeEdit.getSelectedValue();
detailPanel.mapFrom( category );
}
} catch (RaplaException ex) {
showException(ex, getComponent());
}
}
public void stateChanged(ChangeEvent e) {
try {
confirmEdits();
} catch (RaplaException ex) {
showException(ex, getComponent());
}
}
}
public JComponent getComponent() {
return panel;
}
public int getSelectedIndex() {
return treeEdit.getSelectedIndex();
}
public void setObjects(List<Category> o) throws RaplaException {
this.rootCategory = o.get(0);
updateModel();
}
public void processCreateNew() throws RaplaException {
if ( createNew )
{
createCategory( false);
}
}
private void createCategory(boolean bCreateSubCategory) throws RaplaException {
confirmEdits();
Category newCategory;
NamedNode parentNode;
TreePath path = treeEdit.getTree().getSelectionPath();
if (path == null) {
parentNode = (NamedNode)model.getRoot();
} else {
NamedNode selectedNode = (NamedNode) path.getLastPathComponent();
if (selectedNode.getParent() == null || bCreateSubCategory)
parentNode = selectedNode;
else
parentNode = (NamedNode)selectedNode.getParent();
}
newCategory = createNewNodeAt( parentNode );
updateModel();
NamedNode newNode = (NamedNode)((NamedNode)model.getRoot()).findNodeFor( newCategory );
TreePath selectionPath = new TreePath( newNode.getPath() );
treeEdit.getTree().setSelectionPath( selectionPath );
detailPanel.name.selectAll();
detailPanel.name.requestFocus();
}
private String createNewKey(Category[] subCategories) {
int max = 1;
for (int i=0;i<subCategories.length;i++) {
String key = subCategories[i].getKey();
if (key.length()>1
&& key.charAt(0) =='c'
&& Character.isDigit(key.charAt(1))
)
{
try {
int value = Integer.valueOf(key.substring(1)).intValue();
if (value >= max)
max = value + 1;
} catch (NumberFormatException ex) {
}
}
}
return "c" + (max);
}
// creates a new Category
private Category createNewNodeAt(NamedNode parentNode) throws RaplaException {
Category newCategory = getModification().newCategory();
Category parent = (Category) parentNode.getUserObject();
newCategory.setKey(createNewKey(parent.getCategories()));
newCategory.getName().setName(getI18n().getLang(), getString("new_category") );
parent.addCategory(newCategory);
getLogger().debug(" new category " + newCategory + " added to " + parent);
return newCategory;
}
private void removeCategory()
{
TreePath[] paths = treeEdit.getTree().getSelectionPaths();
if ( paths == null )
return;
NamedNode[] categoryNodes = new NamedNode[paths.length];
for (int i=0;i<paths.length;i++) {
categoryNodes[i] = (NamedNode) paths[i].getLastPathComponent();
}
removeNodes(categoryNodes);
updateModel();
}
private void moveCategory( int direction )
{
TreePath[] paths = treeEdit.getTree().getSelectionPaths();
if ( paths == null || paths.length == 0)
return;
NamedNode categoryNode = (NamedNode)paths[0].getLastPathComponent();
if ( categoryNode == null)
{
return;
}
Category selectedCategory = (Category)categoryNode.getUserObject();
Category parent = selectedCategory.getParent();
if ( parent == null || selectedCategory.equals( rootCategory))
return;
Category[] childs = parent.getCategories();
for ( int i=0;i<childs.length;i++)
{
parent.removeCategory( childs[i]);
}
if ( direction == -1)
{
Category last = null;
for ( int i=0;i<childs.length;i++)
{
Category current = childs[i];
if ( current.equals( selectedCategory)) {
parent.addCategory( current);
}
if ( last != null && !last.equals( selectedCategory))
{
parent.addCategory(last);
}
last = current;
}
if (last != null && !last.equals( selectedCategory)) {
parent.addCategory(last);
}
}
else
{
boolean insertNow = false;
for ( int i=0;i<childs.length;i++)
{
Category current = childs[i];
if ( !current.equals( selectedCategory)) {
parent.addCategory( current);
} else {
insertNow = true;
continue;
}
if ( insertNow)
{
insertNow = false;
parent.addCategory( selectedCategory);
}
}
if ( insertNow) {
parent.addCategory( selectedCategory);
}
}
updateModel();
}
public void removeNodes(NamedNode[] nodes) {
ArrayList<NamedNode> childList = new ArrayList<NamedNode>();
TreeNode[] path = null;
NamedNode parentNode = null;
for (int i=0;i<nodes.length;i++) {
if (parentNode == null) {
path= nodes[i].getPath();
parentNode = (NamedNode)nodes[i].getParent();
}
// dont't delete the root-node
if (parentNode == null)
continue;
int index = parentNode.getIndexOfUserObject(nodes[i].getUserObject());
if (index >= 0) {
childList.add(nodes[i]);
}
}
if (path != null) {
int size = childList.size();
NamedNode[] childs = new NamedNode[size];
for (int i=0;i<size;i++) {
childs[i] = childList.get(i);
}
for (int i=0;i<size;i++) {
Category subCategory = (Category)childs[i].getUserObject();
subCategory.getParent().removeCategory(subCategory);
getLogger().debug("category removed " + subCategory);
}
}
}
public void mapToObjects() throws RaplaException {
validate( this.rootCategory );
confirmEdits();
}
public List<Category> getObjects() {
return Collections.singletonList(this.rootCategory);
}
private void updateModel() {
model = getTreeFactory().createModel( rootCategory);
RaplaTree.exchangeTreeModel( model , treeEdit.getTree() );
}
public void confirmEdits() throws RaplaException {
if ( getSelectedIndex() < 0 )
return;
Category category = (Category) treeEdit.getSelectedValue();
detailPanel.mapTo ( category );
TreePath path = treeEdit.getTree().getSelectionPath();
if (path != null)
((DefaultTreeModel) model).nodeChanged((TreeNode)path.getLastPathComponent() );
}
private void validate(Category category) throws RaplaException {
checkKey( category.getKey() );
Category[] categories = category.getCategories();
for ( int i=0; i< categories.length;i++) {
validate( categories[i] );
}
}
private void checkKey(String key) throws RaplaException {
if (key.length() ==0)
throw new RaplaException(getString("error.no_key"));
if (!Tools.isKey(key) || key.length()>50)
{
Object[] param = new Object[3];
param[0] = key;
param[1] = "'-', '_'";
param[2] = "'_'";
throw new RaplaException(getI18n().format("error.invalid_key", param));
}
}
public void setEditKeys(boolean editKeys) {
detailPanel.setEditKeys(editKeys);
this.editKeys = editKeys;
}
}
class CategoryDetail extends RaplaGUIComponent
implements
ChangeListener
{
JPanel mainPanel = new JPanel();
Category currentCategory;
JPanel panel = new JPanel();
JLabel nameLabel = new JLabel();
JLabel keyLabel = new JLabel();
JLabel colorLabel = new JLabel();
MultiLanguageField name;
TextField key;
TextField colorTextField;
JPanel colorPanel = new JPanel();
RaplaArrowButton addButton = new RaplaArrowButton('>', 25);
RaplaArrowButton removeButton = new RaplaArrowButton('<', 25);
public CategoryDetail(RaplaContext context)
{
super( context);
name = new MultiLanguageField(context);
key = new TextField(context);
colorTextField = new TextField(context);
double fill = TableLayout.FILL;
double pre = TableLayout.PREFERRED;
panel.setLayout( new TableLayout( new double[][]
{{5, pre, 5, fill }, // Columns
{5, pre ,5, pre, 5, pre, 5}} // Rows
));
panel.add("1,1,l,f", nameLabel);
panel.add("3,1,f,f", name.getComponent() );
panel.add("1,3,l,f", keyLabel);
panel.add("3,3,f,f", key.getComponent() );
panel.add("1,5,l,f", colorLabel);
panel.add("3,5,f,f", colorPanel);
colorPanel.setLayout( new BorderLayout());
colorPanel.add( colorTextField.getComponent(), BorderLayout.CENTER );
nameLabel.setText(getString("name") + ":");
keyLabel.setText(getString("key") + ":");
colorLabel.setText( getString("color") + ":");
name.addChangeListener ( this );
key.addChangeListener ( this );
colorTextField.addChangeListener( this );
// Add everything to the MainPanel
mainPanel.setLayout(new BorderLayout());
mainPanel.add(panel, BorderLayout.NORTH);
}
class CategoryListCellRenderer extends DefaultListCellRenderer {
private static final long serialVersionUID = 1L;
private boolean filterStyle;
public CategoryListCellRenderer(boolean filterStyle) {
this.filterStyle = filterStyle;
}
public CategoryListCellRenderer() {
this(false);
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected,
cellHasFocus);
if (filterStyle == true)
setFont((getFont().deriveFont(Font.PLAIN)));
if (value != null && value instanceof Category) {
setText(((Category) value).getName(getLocale()));
}
return this;
}
}
public void requestFocus() {
name.requestFocus();
}
public void setEditKeys(boolean editKeys) {
keyLabel.setVisible( editKeys );
key.getComponent().setVisible( editKeys );
colorLabel.setVisible( editKeys );
colorTextField.getComponent().setVisible( editKeys );
}
public JComponent getComponent() {
return mainPanel;
}
public void mapFrom(Category category) {
name.setValue( category.getName());
key.setValue( category.getKey());
String color = category.getAnnotation( CategoryAnnotations.KEY_NAME_COLOR);
if ( color != null)
{
colorTextField.setValue( color );
}
else
{
colorTextField.setValue( null );
}
currentCategory = category;
}
public void mapTo(Category category) throws RaplaException {
category.getName().setTo( name.getValue());
category.setKey( key.getValue());
String colorValue = colorTextField.getValue().toString().trim();
if ( colorValue.length() > 0) {
category.setAnnotation(CategoryAnnotations.KEY_NAME_COLOR, colorValue );
} else {
category.setAnnotation(CategoryAnnotations.KEY_NAME_COLOR, null );
}
}
public void stateChanged(ChangeEvent e) {
fireContentChanged();
}
ArrayList<ChangeListener> listenerList = new ArrayList<ChangeListener>();
public void addChangeListener(ChangeListener listener) {
listenerList.add(listener);
}
public void removeChangeListener(ChangeListener listener) {
listenerList.remove(listener);
}
public ChangeListener[] getChangeListeners() {
return listenerList.toArray(new ChangeListener[]{});
}
protected void fireContentChanged() {
if (listenerList.size() == 0)
return;
ChangeEvent evt = new ChangeEvent(this);
ChangeListener[] listeners = getChangeListeners();
for (int i = 0;i<listeners.length; i++) {
listeners[i].stateChanged(evt);
}
}
}
| 04900db4-rob | src/org/rapla/gui/internal/edit/CategoryEditUI.java | Java | gpl3 | 19,729 |
package org.rapla.gui.internal.edit;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListModel;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.rapla.components.calendar.NavButton;
import org.rapla.components.calendar.RaplaArrowButton;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.xmlbundle.I18nBundle;
import org.rapla.gui.toolkit.AWTColorUtil;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaWidget;
final public class RaplaListEdit<T> implements
RaplaWidget
{
boolean coloredBackground = false;
int[] oldIndex = new int[0];
JPanel mainPanel = new JPanel();
JPanel statusBar = new JPanel();
JPanel identifierPanel = new JPanel();
JLabel identifier = new JLabel();
JLabel nothingSelectedLabel = new JLabel();
JScrollPane scrollPane;
NavButton prev = new NavButton('^');
NavButton next = new NavButton('v');
RaplaArrowButton moveUpButton = new RaplaArrowButton('^', 25);
RaplaArrowButton moveDownButton = new RaplaArrowButton('v', 25);
Color selectionBackground = UIManager.getColor("List.selectionBackground");
Color background = UIManager.getColor("List.background");
JPanel jointPanel = new JPanel() {
private static final long serialVersionUID = 1L;
int xa[] = new int[4];
int ya[] = new int[4];
public void paint(Graphics g) {
super.paint(g);
Dimension dim = getSize();
int index = list.getSelectedIndex();
Rectangle rect = list.getCellBounds(index,index);
if (rect != null) {
int y = rect.y -scrollPane.getViewport().getViewPosition().y;
int y1= Math.min(dim.height,Math.max(0, y) + scrollPane.getLocation().y);
int y2= Math.min(dim.height,Math.max(0,y + rect.height) + scrollPane.getLocation().y);
xa[0]=0;
ya[0]=y1;
xa[1]=dim.width;
ya[1]=0;
xa[2]=dim.width;
ya[2]=dim.height;
xa[3]=0;
ya[3]=y2;
g.setColor(selectionBackground);
g.fillPolygon(xa,ya,4);
g.setColor(background);
g.drawLine(xa[0],ya[0],xa[1],ya[1]);
g.drawLine(xa[3],ya[3],xa[2],ya[2]);
}
}
};
JPanel content = new JPanel();
JPanel detailContainer = new JPanel();
JPanel editPanel = new JPanel();
JList list = new JList() {
private static final long serialVersionUID = 1L;
@SuppressWarnings("unchecked")
public void setModel(ListModel model) {
super.setModel( model );
model.addListDataListener(new ListDataListener() {
public void contentsChanged(ListDataEvent e) {
modelUpdate();
}
public void intervalAdded(ListDataEvent e) {
}
public void intervalRemoved(ListDataEvent e) {
}
});
}
};
public RaplaButton createNewButton = new RaplaButton();
public RaplaButton removeButton = new RaplaButton();
CardLayout cardLayout = new CardLayout();
private Listener listener = new Listener();
private ActionListener callback;
JPanel toolbar = new JPanel();
public RaplaListEdit(I18nBundle i18n, JComponent detailContent,ActionListener callback)
{
this.callback = callback;
toolbar.setLayout( new BoxLayout( toolbar, BoxLayout.X_AXIS));
toolbar.add(createNewButton);
toolbar.add(removeButton);
toolbar.add(Box.createHorizontalStrut(5));
toolbar.add(moveUpButton);
toolbar.add(moveDownButton);
mainPanel.setLayout(new TableLayout(new double[][] {
{TableLayout.PREFERRED,TableLayout.PREFERRED,TableLayout.FILL}
,{TableLayout.FILL}
}));
jointPanel.setPreferredSize(new Dimension(15,50));
mainPanel.add(content,"0,0");
mainPanel.add(jointPanel,"1,0");
mainPanel.add(editPanel,"2,0");
editPanel.setLayout(cardLayout);
editPanel.add(nothingSelectedLabel, "0");
editPanel.add(detailContainer, "1");
content.setLayout(new BorderLayout());
content.add(toolbar,BorderLayout.NORTH);
scrollPane = new JScrollPane(list
,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS
,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setPreferredSize(new Dimension(310,80));
content.add(scrollPane, BorderLayout.CENTER);
content.add(statusBar, BorderLayout.SOUTH);
statusBar.setLayout( new FlowLayout(FlowLayout.LEFT));
detailContainer.setLayout(new BorderLayout());
editPanel.setBorder(BorderFactory.createRaisedBevelBorder());
detailContainer.add(identifierPanel,BorderLayout.WEST);
detailContainer.add(detailContent, BorderLayout.CENTER);
//mainPanel.setBorder(new LineBorder(Color.black));
identifierPanel.setLayout(new BorderLayout());
identifierPanel.add(prev,BorderLayout.NORTH);
identifierPanel.add(identifier,BorderLayout.CENTER);
identifierPanel.add(next,BorderLayout.SOUTH);
identifier.setBorder(new EmptyBorder(0,5,0,5));
next.addActionListener(listener);
prev.addActionListener(listener);
removeButton.addActionListener(listener);
createNewButton.addActionListener(listener);
moveUpButton.addActionListener(listener);
moveDownButton.addActionListener(listener);
scrollPane.getViewport().addChangeListener(listener);
// list.setDragEnabled(true);
list.addMouseListener(listener);
list.addListSelectionListener(listener);
modelUpdate();
createNewButton.setText(i18n.getString("new"));
createNewButton.setIcon(i18n.getIcon("icon.new"));
removeButton.setIcon(i18n.getIcon("icon.delete"));
removeButton.setText(i18n.getString("delete"));
nothingSelectedLabel.setHorizontalAlignment(JLabel.CENTER);
nothingSelectedLabel.setText(i18n.getString("nothing_selected"));
}
public JPanel getToolbar()
{
return toolbar;
}
public JComponent getComponent() {
return mainPanel;
}
public JPanel getStatusBar() {
return statusBar;
}
public JList getList() {
return list;
}
public void setListDimension(Dimension d) {
scrollPane.setPreferredSize(d);
}
public void setMoveButtonVisible(boolean visible) {
moveUpButton.setVisible(visible);
moveDownButton.setVisible(visible);
}
public int getSelectedIndex() {
return list.getSelectedIndex();
}
public void select(int index) {
list.setSelectedIndex(index);
if (index >=0) {
list.ensureIndexIsVisible(index);
}
}
public void setColoredBackgroundEnabled(boolean enable) {
coloredBackground = enable;
}
public boolean isColoredBackgroundEnabled() {
return coloredBackground;
}
private void modelUpdate() {
removeButton.setEnabled(list.getMinSelectionIndex() >=0);
moveUpButton.setEnabled(list.getMinSelectionIndex() > 0);
moveDownButton.setEnabled(list.getMinSelectionIndex() >= 0 &&
list.getMaxSelectionIndex() < (list.getModel().getSize() -1) );
jointPanel.repaint();
}
private void editSelectedEntry() {
Object selected = list.getSelectedValue();
if (selected == null) {
cardLayout.first(editPanel);
callback.actionPerformed(new ActionEvent(this
,ActionEvent.ACTION_PERFORMED
,"select"
)
);
return;
} else {
cardLayout.last(editPanel);
int index = getSelectedIndex();
next.setEnabled((index + 1)<list.getModel().getSize());
prev.setEnabled(index>0);
Color color = AWTColorUtil.getAppointmentColor(0);
if ( isColoredBackgroundEnabled() ) {
color = AWTColorUtil.getAppointmentColor(index);
}
identifierPanel.setBackground(color);
identifier.setText(String.valueOf(index + 1));
callback.actionPerformed(new ActionEvent(this
,ActionEvent.ACTION_PERFORMED
,"select"
)
);
callback.actionPerformed(new ActionEvent(this
,ActionEvent.ACTION_PERFORMED
,"edit"
)
);
}
}
private boolean disableListSelection;
public void updateSort(List<Object> selectedValues) {
ListModel model2 = list.getModel();
int[] index = new int[selectedValues.size()];
int j = 0;
for ( int i=0;i<model2.getSize();i++)
{
Object elementAt = model2.getElementAt( i);
if ( selectedValues.contains( elementAt ))
{
index[j++] = i;
}
}
disableListSelection = true;
list.setSelectedIndices( index);
disableListSelection = false;
}
class Listener extends MouseAdapter implements ListSelectionListener,ActionListener,ChangeListener {
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == next) {
select(Math.min(list.getModel().getSize()-1, getSelectedIndex() + 1));
} else if (evt.getSource() == prev) {
select(Math.max(0, getSelectedIndex()-1));
}
if (evt.getSource() == removeButton) {
callback.actionPerformed(new ActionEvent(RaplaListEdit.this
,ActionEvent.ACTION_PERFORMED
,"remove"
)
);
} else if (evt.getSource() == createNewButton) {
callback.actionPerformed(new ActionEvent(RaplaListEdit.this
,ActionEvent.ACTION_PERFORMED
,"new"
)
);
} else if (evt.getSource() == moveUpButton) {
callback.actionPerformed(new ActionEvent(RaplaListEdit.this
,ActionEvent.ACTION_PERFORMED
,"moveUp"
)
);
} else if (evt.getSource() == moveDownButton) {
callback.actionPerformed(new ActionEvent(RaplaListEdit.this
,ActionEvent.ACTION_PERFORMED
,"moveDown"
)
);
}
}
public void valueChanged(ListSelectionEvent evt) {
if ( disableListSelection )
{
return;
}
//if (evt.getValueIsAdjusting())
//return;
int[] index = list.getSelectedIndices();
if ( index == oldIndex)
{
return;
}
if ( index == null || oldIndex == null || !Arrays.equals( index, oldIndex))
{
oldIndex = index;
editSelectedEntry();
modelUpdate();
}
}
public void stateChanged(ChangeEvent evt) {
if (evt.getSource() == scrollPane.getViewport()) {
jointPanel.repaint();
}
}
}
@SuppressWarnings({ "unchecked", "deprecation" })
public Collection<T> getSelectedValues()
{
return (Collection<T>) Arrays.asList(list.getSelectedValues());
}
@SuppressWarnings("unchecked")
public T getSelectedValue() {
return (T) list.getSelectedValue();
}
}
| 04900db4-rob | src/org/rapla/gui/internal/edit/RaplaListEdit.java | Java | gpl3 | 13,528 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.edit;
import java.util.ArrayList;
import org.rapla.entities.domain.Reservation;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.EditField;
import org.rapla.gui.internal.edit.fields.ClassificationField;
/****************************************************************
* This is the controller-class for the Resource-Edit-Panel *
****************************************************************/
class ReservationEditUI extends AbstractEditUI<Reservation> {
ClassificationField<Reservation> classificationField;
public ReservationEditUI(RaplaContext context) {
super(context);
ArrayList<EditField> fields = new ArrayList<EditField>();
classificationField = new ClassificationField<Reservation>(context);
fields.add( classificationField);
setFields(fields);
}
public void mapToObjects() throws RaplaException {
classificationField.mapTo( objectList);
if ( getName(objectList).length() == 0)
throw new RaplaException(getString("error.no_name"));
}
protected void mapFromObjects() throws RaplaException {
classificationField.mapFrom( objectList);
}
}
| 04900db4-rob | src/org/rapla/gui/internal/edit/ReservationEditUI.java | Java | gpl3 | 2,191 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.edit.reservation;
import java.awt.Component;
import java.awt.Dimension;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JComponent;
import javax.swing.JTree;
import javax.swing.tree.TreeModel;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.Conflict;
import org.rapla.facade.internal.CalendarOptionsImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.ReservationCheck;
import org.rapla.gui.TreeFactory;
import org.rapla.gui.internal.view.TreeFactoryImpl;
import org.rapla.gui.toolkit.DialogUI;
import org.rapla.gui.toolkit.RaplaTree;
public class ConflictReservationCheck extends RaplaGUIComponent implements ReservationCheck
{
public ConflictReservationCheck(RaplaContext context) {
super(context);
}
public boolean check(Reservation reservation, Component sourceComponent) throws RaplaException {
Conflict[] conflicts = getQuery().getConflicts(reservation);
if (conflicts.length == 0) {
return true;
}
boolean showWarning = getQuery().getPreferences().getEntryAsBoolean(CalendarOptionsImpl.SHOW_CONFLICT_WARNING, true);
User user = getUser();
if ( !showWarning && canCreateConflicts( conflicts, user))
{
return true;
}
JComponent content = getConflictPanel(conflicts);
DialogUI dialog = DialogUI.create(
getContext()
,sourceComponent
,true
,content
,new String[] {
getString("continue")
,getString("back")
}
);
dialog.setDefault(1);
dialog.setIcon(getIcon("icon.big_folder_conflicts"));
dialog.getButton(0).setIcon(getIcon("icon.save"));
dialog.getButton(1).setIcon(getIcon("icon.cancel"));
dialog.setTitle(getString("warning.conflict"));
dialog.start();
if (dialog.getSelectedIndex() == 0) {
try {
return true;
} catch (Exception ex) {
showException(ex,sourceComponent);
return false;
}
}
return false;
}
private boolean canCreateConflicts(Conflict[] conflicts, User user)
{
Set<Allocatable> allocatables = new HashSet<Allocatable>();
for (Conflict conflict:conflicts)
{
allocatables.add(conflict.getAllocatable());
}
for ( Allocatable allocatable:allocatables)
{
if ( !allocatable.canCreateConflicts( user))
{
return false;
}
}
return true;
}
private JComponent getConflictPanel(Conflict[] conflicts) throws RaplaException {
TreeFactory treeFactory = getService(TreeFactory.class);
TreeModel treeModel = treeFactory.createConflictModel( Arrays.asList( conflicts));
RaplaTree treeSelection = new RaplaTree();
JTree tree = treeSelection.getTree();
tree.setRootVisible(false);
tree.setShowsRootHandles(true);
tree.setCellRenderer(((TreeFactoryImpl) treeFactory).createConflictRenderer());
treeSelection.exchangeTreeModel(treeModel);
treeSelection.expandAll();
treeSelection.setPreferredSize( new Dimension(400,200));
return treeSelection;
}
}
| 04900db4-rob | src/org/rapla/gui/internal/edit/reservation/ConflictReservationCheck.java | Java | gpl3 | 4,523 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.edit.reservation;
import java.awt.Component;
import java.awt.Container;
import java.awt.Point;
import java.awt.datatransfer.StringSelection;
import java.security.AccessControlException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.swing.Icon;
import org.rapla.client.RaplaClientExtensionPoints;
import org.rapla.components.iolayer.IOInterface;
import org.rapla.components.util.Command;
import org.rapla.components.util.DateTools;
import org.rapla.components.util.TimeInterval;
import org.rapla.components.util.undo.CommandHistory;
import org.rapla.components.util.undo.CommandUndo;
import org.rapla.entities.EntityNotFoundException;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentBlock;
import org.rapla.entities.domain.Repeating;
import org.rapla.entities.domain.Reservation;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.ModificationListener;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.ReservationCheck;
import org.rapla.gui.ReservationController;
import org.rapla.gui.ReservationEdit;
import org.rapla.gui.internal.common.RaplaClipboard;
import org.rapla.gui.internal.edit.DeleteUndo;
import org.rapla.gui.internal.edit.SaveUndo;
import org.rapla.gui.internal.view.HTMLInfo.Row;
import org.rapla.gui.internal.view.ReservationInfoUI;
import org.rapla.gui.toolkit.DialogUI;
public class ReservationControllerImpl extends RaplaGUIComponent implements ModificationListener, ReservationController
{
/** We store all open ReservationEditWindows with their reservationId
* in a map, to lookup if the reservation is already beeing edited.
That prevents editing the same Reservation in different windows
*/
Collection<ReservationEditImpl> editWindowList = new ArrayList<ReservationEditImpl>();
public ReservationControllerImpl(RaplaContext sm)
{
super(sm);
getUpdateModule().addModificationListener(this);
}
void addReservationEdit(ReservationEdit editWindow) {
editWindowList.add((ReservationEditImpl)editWindow);
}
void removeReservationEdit(ReservationEdit editWindow) {
editWindowList.remove(editWindow);
}
public ReservationEdit edit(Reservation reservation) throws RaplaException {
return startEdit(reservation,null);
}
public ReservationEdit edit(AppointmentBlock appointmentBlock)throws RaplaException {
return startEdit(appointmentBlock.getAppointment().getReservation(), appointmentBlock);
}
public ReservationEdit[] getEditWindows() {
return editWindowList.toArray( new ReservationEdit[] {});
}
private ReservationEditImpl newEditWindow() throws RaplaException {
ReservationEditImpl c = new ReservationEditImpl(getContext());
return c;
}
private ReservationEdit startEdit(Reservation reservation,AppointmentBlock appointmentBlock)
throws RaplaException {
// Lookup if the reservation is already beeing edited
ReservationEditImpl c = null;
Iterator<ReservationEditImpl> it = editWindowList.iterator();
while (it.hasNext()) {
c = it.next();
if (c.getReservation().isIdentical(reservation))
break;
else
c = null;
}
if (c != null) {
c.frame.requestFocus();
c.frame.toFront();
} else {
c = newEditWindow();
// only is allowed to exchange allocations
c.editReservation(reservation, appointmentBlock);
if ( !canModify( reservation) )
{
c.deleteButton.setEnabled( false);
disableComponentAndAllChildren(c.appointmentEdit.getComponent());
disableComponentAndAllChildren(c.reservationInfo.getComponent());
}
}
return c;
}
static void disableComponentAndAllChildren(Container component) {
component.setEnabled( false );
Component[] components = component.getComponents();
for ( int i=0; i< components.length; i++)
{
if ( components[i] instanceof Container) {
disableComponentAndAllChildren( (Container) components[i] );
}
}
}
public void deleteBlocks(Collection<AppointmentBlock> blockList,
Component parent, Point point) throws RaplaException
{
DialogUI dlg = getInfoFactory().createDeleteDialog(blockList.toArray(), parent);
dlg.start();
if (dlg.getSelectedIndex() != 0)
return;
Set<Appointment> appointmentsToRemove = new LinkedHashSet<Appointment>();
HashMap<Appointment,List<Date>> exceptionsToAdd = new LinkedHashMap<Appointment,List<Date>>();
HashMap<Reservation,Integer> appointmentsRemoved = new LinkedHashMap<Reservation,Integer>();
Set<Reservation> reservationsToRemove = new LinkedHashSet<Reservation>();
for ( AppointmentBlock block: blockList)
{
Appointment appointment = block.getAppointment();
Date from = new Date(block.getStart());
Repeating repeating = appointment.getRepeating();
boolean exceptionsAdded = false;
if ( repeating != null)
{
List<Date> dateList = exceptionsToAdd.get( appointment );
if ( dateList == null)
{
dateList = new ArrayList<Date>();
exceptionsToAdd.put( appointment,dateList);
}
dateList.add(from);
if ( isNotEmptyWithExceptions(appointment, dateList))
{
exceptionsAdded = true;
}
else
{
exceptionsToAdd.remove( appointment);
}
}
if (!exceptionsAdded)
{
boolean added = appointmentsToRemove.add(appointment);
if ( added)
{
Reservation reservation = appointment.getReservation();
Integer count = appointmentsRemoved.get(reservation);
if ( count == null)
{
count = 0;
}
count++;
appointmentsRemoved.put( reservation, count);
}
}
}
for (Reservation reservation: appointmentsRemoved.keySet())
{
Integer count = appointmentsRemoved.get( reservation);
Appointment[] appointments = reservation.getAppointments();
if ( count == appointments.length)
{
reservationsToRemove.add( reservation);
for (Appointment appointment:appointments)
{
appointmentsRemoved.remove(appointment);
}
}
}
DeleteBlocksCommand command = new DeleteBlocksCommand(reservationsToRemove, appointmentsToRemove, exceptionsToAdd);
CommandHistory commanHistory = getModification().getCommandHistory();
commanHistory.storeAndExecute( command);
}
class DeleteBlocksCommand extends DeleteUndo<Reservation>
{
Set<Reservation> reservationsToRemove;
Set<Appointment> appointmentsToRemove;
Map<Appointment, List<Date>> exceptionsToAdd;
private Map<Appointment,Allocatable[]> allocatablesRemoved = new HashMap<Appointment,Allocatable[]>();
private Map<Appointment,Reservation> parentReservations = new HashMap<Appointment,Reservation>();
public DeleteBlocksCommand(Set<Reservation> reservationsToRemove, Set<Appointment> appointmentsToRemove, Map<Appointment, List<Date>> exceptionsToAdd) {
super( ReservationControllerImpl.this.getContext(),reservationsToRemove);
this.reservationsToRemove = reservationsToRemove;
this.appointmentsToRemove = appointmentsToRemove;
this.exceptionsToAdd = exceptionsToAdd;
}
public boolean execute() throws RaplaException {
HashMap<Reservation,Reservation> toUpdate = new LinkedHashMap<Reservation,Reservation>();
allocatablesRemoved.clear();
for (Appointment appointment:appointmentsToRemove)
{
Reservation reservation = appointment.getReservation();
if ( reservationsToRemove.contains( reservation))
{
continue;
}
parentReservations.put(appointment, reservation);
Reservation mutableReservation= toUpdate.get(reservation);
if ( mutableReservation == null)
{
mutableReservation = getModification().edit( reservation);
toUpdate.put( reservation, mutableReservation);
}
Allocatable[] restrictedAllocatables = mutableReservation.getRestrictedAllocatables(appointment);
mutableReservation.removeAppointment( appointment);
allocatablesRemoved.put( appointment, restrictedAllocatables);
}
for (Appointment appointment:exceptionsToAdd.keySet())
{
Reservation reservation = appointment.getReservation();
if ( reservationsToRemove.contains( reservation))
{
continue;
}
Reservation mutableReservation= toUpdate.get(reservation);
if ( mutableReservation == null)
{
mutableReservation = getModification().edit( reservation);
toUpdate.put( reservation, mutableReservation);
}
Appointment found = mutableReservation.findAppointment( appointment);
if ( found != null)
{
Repeating repeating = found.getRepeating();
if ( repeating != null)
{
List<Date> list = exceptionsToAdd.get( appointment);
for (Date exception: list)
{
repeating.addException( exception);
}
}
}
}
Reservation[] updateArray = toUpdate.values().toArray(Reservation.RESERVATION_ARRAY);
Reservation[] removeArray = reservationsToRemove.toArray( Reservation.RESERVATION_ARRAY);
getModification().storeAndRemove(updateArray, removeArray);
return true;
}
public boolean undo() throws RaplaException {
if (!super.undo())
{
return false;
}
HashMap<Reservation,Reservation> toUpdate = new LinkedHashMap<Reservation,Reservation>();
for (Appointment appointment:appointmentsToRemove)
{
Reservation reservation = parentReservations.get(appointment);
Reservation mutableReservation= toUpdate.get(reservation);
if ( mutableReservation == null)
{
mutableReservation = getModification().edit( reservation);
toUpdate.put( reservation, mutableReservation);
}
mutableReservation.addAppointment( appointment);
Allocatable[] removedAllocatables = allocatablesRemoved.get( appointment);
mutableReservation.setRestriction( appointment, removedAllocatables);
}
for (Appointment appointment:exceptionsToAdd.keySet())
{
Reservation reservation = appointment.getReservation();
Reservation mutableReservation= toUpdate.get(reservation);
if ( mutableReservation == null)
{
mutableReservation = getModification().edit( reservation);
toUpdate.put( reservation, mutableReservation);
}
Appointment found = mutableReservation.findAppointment( appointment);
if ( found != null)
{
Repeating repeating = found.getRepeating();
if ( repeating != null)
{
List<Date> list = exceptionsToAdd.get( appointment);
for (Date exception: list)
{
repeating.removeException( exception);
}
}
}
}
Reservation[] updateArray = toUpdate.values().toArray(Reservation.RESERVATION_ARRAY);
Reservation[] removeArray = Reservation.RESERVATION_ARRAY;
getModification().storeAndRemove(updateArray,removeArray);
return true;
}
public String getCommandoName()
{
return getString("delete") + " " + getString("appointments");
}
}
public void deleteAppointment(AppointmentBlock appointmentBlock, Component sourceComponent, Point point) throws RaplaException {
boolean includeEvent = true;
Appointment appointment = appointmentBlock.getAppointment();
final DialogAction dialogResult = showDialog(appointmentBlock, "delete", includeEvent, sourceComponent, point);
Set<Appointment> appointmentsToRemove = new LinkedHashSet<Appointment>();
HashMap<Appointment,List<Date>> exceptionsToAdd = new LinkedHashMap<Appointment,List<Date>>();
Set<Reservation> reservationsToRemove = new LinkedHashSet<Reservation>();
final Date startDate = new Date(appointmentBlock.getStart());
switch (dialogResult) {
case SINGLE:
Repeating repeating = appointment.getRepeating();
if ( repeating != null )
{
List<Date> exceptionList = Collections.singletonList( startDate);
if ( isNotEmptyWithExceptions(appointment, exceptionList))
{
exceptionsToAdd.put( appointment,exceptionList);
}
else
{
appointmentsToRemove.add( appointment);
}
}
else
{
appointmentsToRemove.add( appointment);
}
break;
case EVENT:
reservationsToRemove.add( appointment.getReservation());
break;
case SERIE:
appointmentsToRemove.add( appointment);
break;
case CANCEL:
return;
}
DeleteBlocksCommand command = new DeleteBlocksCommand(reservationsToRemove, appointmentsToRemove, exceptionsToAdd)
{
public String getCommandoName() {
String name;
if (dialogResult == DialogAction.SINGLE)
name =getI18n().format("single_appointment.format",startDate);
else if (dialogResult == DialogAction.EVENT)
name = getString("reservation");
else if (dialogResult == DialogAction.SERIE)
name = getString("serie");
else
name = getString("appointment");
return getString("delete") + " " + name;
}
};
CommandHistory commandHistory = getModification().getCommandHistory();
commandHistory.storeAndExecute( command );
}
private boolean isNotEmptyWithExceptions(Appointment appointment, List<Date> exceptions) {
Repeating repeating = appointment.getRepeating();
if ( repeating != null)
{
int number = repeating.getNumber();
if ( number>=1)
{
if (repeating.getExceptions().length >= number-1)
{
Collection<AppointmentBlock> blocks = new ArrayList<AppointmentBlock>();
appointment.createBlocks(appointment.getStart(), appointment.getMaxEnd(), blocks);
int blockswithException = 0;
for (AppointmentBlock block:blocks)
{
long start = block.getStart();
boolean blocked = false;
for (Date excepion: exceptions)
{
if (DateTools.isSameDay(excepion.getTime(), start))
{
blocked = true;
}
}
if ( blocked)
{
blockswithException++;
}
}
if ( blockswithException >= blocks.size())
{
return false;
}
}
}
}
return true;
}
public Appointment copyAppointment(Appointment appointment) throws RaplaException {
return getModification().clone(appointment);
}
enum DialogAction
{
EVENT,
SERIE,
SINGLE,
CANCEL
}
private DialogAction showDialog(AppointmentBlock appointmentBlock
,String action
,boolean includeEvent
,Component sourceComponent
,Point point
) throws RaplaException
{
Appointment appointment = appointmentBlock.getAppointment();
Date from = new Date(appointmentBlock.getStart());
Reservation reservation = appointment.getReservation();
getLogger().debug(action + " '" + appointment + "' for reservation '" + reservation + "'");
List<String> optionList = new ArrayList<String>();
List<Icon> iconList = new ArrayList<Icon>();
List<DialogAction> actionList = new ArrayList<ReservationControllerImpl.DialogAction>();
String dateString = getRaplaLocale().formatDate(from);
if ( reservation.getAppointments().length <=1 || includeEvent)
{
optionList.add(getString("reservation"));
iconList.add(getIcon("icon.edit_window_small"));
actionList.add(DialogAction.EVENT);
}
if ( appointment.getRepeating() != null && reservation.getAppointments().length > 1 )
{
String shortSummary = getAppointmentFormater().getShortSummary(appointment);
optionList.add(getString("serie") + ": " + shortSummary);
iconList.add(getIcon("icon.repeating"));
actionList.add(DialogAction.SERIE);
}
if ( (appointment.getRepeating() != null && isNotEmptyWithExceptions( appointment, Collections.singletonList(from)))|| reservation.getAppointments().length > 1)
{
optionList.add(getI18n().format("single_appointment.format",dateString));
iconList.add(getIcon("icon.single"));
actionList.add( DialogAction.SINGLE);
}
if (optionList.size() > 1) {
DialogUI dialog = DialogUI.create(
getContext()
,sourceComponent
,true
,getString(action)
,getString(action+ "_appointment.format")
,optionList.toArray(new String[] {})
);
dialog.setIcon(getIcon("icon.question"));
for ( int i=0;i< optionList.size();i++)
{
dialog.getButton(i).setIcon(iconList.get( i));
}
dialog.start(point);
int index = dialog.getSelectedIndex();
if ( index < 0)
{
return DialogAction.CANCEL;
}
return actionList.get(index);
}
else
{
if ( action.equals("delete"))
{
DialogUI dlg = getInfoFactory().createDeleteDialog( new Object[]{ appointment.getReservation()}, sourceComponent);
dlg.start();
if (dlg.getSelectedIndex() != 0)
return DialogAction.CANCEL;
}
}
if ( actionList.size() > 0)
{
return actionList.get( 0 );
}
return DialogAction.EVENT;
}
public Appointment copyAppointment(
AppointmentBlock appointmentBlock
,Component sourceComponent
,Point point
,Collection<Allocatable> contextAllocatables
)
throws RaplaException
{
RaplaClipboard raplaClipboard = getClipboard();
Appointment appointment = appointmentBlock.getAppointment();
DialogAction result = showDialog(appointmentBlock, "copy", true, sourceComponent, point);
Reservation sourceReservation = appointment.getReservation();
// copy info text to system clipboard
{
StringBuffer buf = new StringBuffer();
ReservationInfoUI reservationInfoUI = new ReservationInfoUI(getContext());
boolean excludeAdditionalInfos = false;
List<Row> attributes = reservationInfoUI.getAttributes(sourceReservation, null, null, excludeAdditionalInfos);
for (Row row:attributes)
{
buf.append( row.getField());
}
String string = buf.toString();
try
{
final IOInterface service = getIOService();
if (service != null) {
StringSelection transferable = new StringSelection(string);
service.setContents(transferable, null);
}
}
catch (AccessControlException ex)
{
}
}
Allocatable[] restrictedAllocatables = sourceReservation.getRestrictedAllocatables(appointment);
if ( result == DialogAction.SINGLE)
{
Appointment copy = copyAppointment(appointment);
copy.setRepeatingEnabled(false);
Calendar cal = getRaplaLocale().createCalendar();
cal.setTime( copy.getStart());
int hour_of_day = cal.get( Calendar.HOUR_OF_DAY);
int minute = cal.get( Calendar.MINUTE);
int second = cal.get( Calendar.SECOND);
cal.setTimeInMillis( appointmentBlock.getStart());
cal.set( Calendar.HOUR_OF_DAY, hour_of_day);
cal.set( Calendar.MINUTE,minute);
cal.set( Calendar.SECOND,second);
cal.set( Calendar.MILLISECOND,0);
Date newStart = cal.getTime();
copy.move(newStart);
raplaClipboard.setAppointment(copy, false, sourceReservation, restrictedAllocatables, contextAllocatables);
return copy;
}
else if ( result == DialogAction.EVENT && appointment.getReservation().getAppointments().length >1)
{
int num = getAppointmentIndex(appointment);
Reservation reservation = appointment.getReservation();
Reservation clone = getModification().clone( reservation);
Appointment[] clonedAppointments = clone.getAppointments();
if ( num >= clonedAppointments.length)
{
return null;
}
Appointment clonedAppointment = clonedAppointments[num];
boolean wholeReservation = true;
raplaClipboard.setAppointment(clonedAppointment, wholeReservation, clone, restrictedAllocatables, contextAllocatables);
return clonedAppointment;
}
else
{
Appointment copy = copyAppointment(appointment);
raplaClipboard.setAppointment(copy, false, sourceReservation, restrictedAllocatables, contextAllocatables);
return copy;
}
}
public int getAppointmentIndex(Appointment appointment) {
int num;
Reservation reservation = appointment.getReservation();
num = 0;
for (Appointment app:reservation.getAppointments())
{
if ( appointment.equals(app))
{
break;
}
num++;
}
return num;
}
public void dataChanged(ModificationEvent evt) throws RaplaException {
// we need to clone the list, because it could be modified during edit
ArrayList<ReservationEditImpl> clone = new ArrayList<ReservationEditImpl>(editWindowList);
for ( ReservationEditImpl c:clone)
{
c.refresh(evt);
TimeInterval invalidateInterval = evt.getInvalidateInterval();
Reservation original = c.getOriginal();
if ( invalidateInterval != null && original != null)
{
boolean test = false;
for (Appointment app:original.getAppointments())
{
if ( app.overlaps( invalidateInterval))
{
test = true;
}
}
if ( test )
{
try
{
Reservation persistant = getModification().getPersistant( original);
Date version = persistant.getLastChanged();
Date originalVersion = original.getLastChanged();
if ( originalVersion != null && version!= null && originalVersion.before( version))
{
c.updateReservation(persistant);
}
}
catch (EntityNotFoundException ex)
{
c.deleteReservation();
}
}
}
}
}
private RaplaClipboard getClipboard()
{
return getService(RaplaClipboard.class);
}
public boolean isAppointmentOnClipboard() {
return (getClipboard().getAppointment() != null || !getClipboard().getReservations().isEmpty());
}
public void pasteAppointment(Date start, Component sourceComponent, Point point, boolean asNewReservation, boolean keepTime) throws RaplaException {
RaplaClipboard clipboard = getClipboard();
Collection<Reservation> reservations = clipboard.getReservations();
CommandUndo<RaplaException> pasteCommand;
if ( reservations.size() > 1)
{
pasteCommand = new ReservationPaste(reservations, start);
}
else
{
Appointment appointment = clipboard.getAppointment();
if (appointment == null) {
return;
}
Reservation reservation = clipboard.getReservation();
boolean copyWholeReservation = clipboard.isWholeReservation();
Allocatable[] restrictedAllocatables = clipboard.getRestrictedAllocatables();
long offset = getOffset(appointment.getStart(), start, keepTime);
getLogger().debug("Paste appointment '" + appointment
+ "' for reservation '" + reservation
+ "' at " + start);
Collection<Allocatable> currentlyMarked = getService(CalendarSelectionModel.class).getMarkedAllocatables();
Collection<Allocatable> previouslyMarked = clipboard.getConextAllocatables();
// exchange allocatables if pasted in a different allocatable slot
if ( copyWholeReservation && currentlyMarked != null && previouslyMarked != null && currentlyMarked.size() == 1 && previouslyMarked.size() == 1)
{
Allocatable newAllocatable = currentlyMarked.iterator().next();
Allocatable oldAllocatable = previouslyMarked.iterator().next();
if ( !newAllocatable.equals( oldAllocatable))
{
if ( !reservation.hasAllocated(newAllocatable))
{
AppointmentBlock appointmentBlock = new AppointmentBlock(appointment);
AllocatableExchangeCommand cmd = exchangeAllocatebleCmd(appointmentBlock, oldAllocatable, newAllocatable,null, sourceComponent, point);
reservation = cmd.getModifiedReservationForExecute();
appointment = reservation.getAppointments()[0];
}
}
}
pasteCommand = new AppointmentPaste(appointment, reservation, restrictedAllocatables, asNewReservation, copyWholeReservation, offset, sourceComponent);
}
getClientFacade().getCommandHistory().storeAndExecute(pasteCommand);
}
public void moveAppointment(AppointmentBlock appointmentBlock,Date newStart,Component sourceComponent,Point p, boolean keepTime) throws RaplaException {
Date from = new Date( appointmentBlock.getStart());
if ( newStart.equals(from))
return;
getLogger().debug("Moving appointment " + appointmentBlock.getAppointment() + " from " + from + " to " + newStart);
resizeAppointment(appointmentBlock, newStart, null, sourceComponent, p, keepTime);
}
public void resizeAppointment(AppointmentBlock appointmentBlock, Date newStart, Date newEnd, Component sourceComponent, Point p, boolean keepTime) throws RaplaException {
boolean includeEvent = newEnd == null;
Appointment appointment = appointmentBlock.getAppointment();
Date from = new Date(appointmentBlock.getStart());
DialogAction result = showDialog(appointmentBlock, "move", includeEvent, sourceComponent, p);
if (result == DialogAction.CANCEL) {
return;
}
Date oldStart = from;
Date oldEnd = (newEnd == null) ? null : new Date(from.getTime() + appointment.getEnd().getTime() - appointment.getStart().getTime());
if ( keepTime && newStart != null && !newStart.equals( oldStart))
{
newStart = new Date( oldStart.getTime() + getOffset(oldStart, newStart, keepTime));
}
AppointmentResize resizeCommand = new AppointmentResize(appointment, oldStart, oldEnd, newStart, newEnd, sourceComponent, result, keepTime);
getClientFacade().getCommandHistory().storeAndExecute(resizeCommand);
}
public long getOffset(Date appStart, Date newStart, boolean keepTime) {
Calendar calendar = getRaplaLocale().createCalendar();
calendar.setTime( newStart);
if ( keepTime)
{
Calendar cal2 = getRaplaLocale().createCalendar();
cal2.setTime( appStart);
calendar.set(Calendar.HOUR_OF_DAY, cal2.get( Calendar.HOUR_OF_DAY));
calendar.set(Calendar.MINUTE, cal2.get( Calendar.MINUTE));
calendar.set(Calendar.SECOND, cal2.get( Calendar.SECOND));
calendar.set(Calendar.MILLISECOND, cal2.get( Calendar.MILLISECOND));
}
Date newStartAdjusted = calendar.getTime();
long offset = newStartAdjusted.getTime() - appStart.getTime();
return offset;
}
public boolean save(Reservation reservation, Component sourceComponent) throws RaplaException {
SaveCommand saveCommand = new SaveCommand(reservation);
save(reservation, sourceComponent, saveCommand);
return saveCommand.hasSaved();
}
boolean save(Reservation reservation,Component sourceComponent,Command saveCommand) throws RaplaException {
Collection<ReservationCheck> checkers = getContainer().lookupServicesFor(RaplaClientExtensionPoints.RESERVATION_SAVE_CHECK);
for (ReservationCheck check:checkers)
{
boolean successful= check.check(reservation, sourceComponent);
if ( !successful)
{
return false;
}
}
try {
saveCommand.execute();
return true;
} catch (Exception ex) {
showException(ex,sourceComponent);
return false;
}
}
class SaveCommand implements Command {
private final Reservation reservation;
boolean saved;
public SaveCommand(Reservation reservation) {
this.reservation = reservation;
}
public void execute() throws RaplaException {
getModification().store( reservation );
saved = true;
}
public boolean hasSaved() {
return saved;
}
}
@Override
public void exchangeAllocatable(final AppointmentBlock appointmentBlock,final Allocatable oldAllocatable,final Allocatable newAllocatable,final Date newStart,final Component sourceComponent, final Point point)
throws RaplaException
{
AllocatableExchangeCommand command = exchangeAllocatebleCmd( appointmentBlock, oldAllocatable, newAllocatable,newStart, sourceComponent, point);
if ( command != null)
{
CommandHistory commandHistory = getModification().getCommandHistory();
commandHistory.storeAndExecute( command );
}
}
protected AllocatableExchangeCommand exchangeAllocatebleCmd(AppointmentBlock appointmentBlock, final Allocatable oldAllocatable,final Allocatable newAllocatable, Date newStart,final Component sourceComponent, final Point point) throws RaplaException {
Map<Allocatable,Appointment[]> newRestrictions = new HashMap<Allocatable, Appointment[]>();
//Appointment appointment;
//Allocatable oldAllocatable;
//Allocatable newAllocatable;
boolean removeAllocatable = false;
boolean addAllocatable = false;
Appointment addAppointment = null;
List<Date> exceptionsAdded = new ArrayList<Date>();
Appointment appointment = appointmentBlock.getAppointment();
Reservation reservation = appointment.getReservation();
Date date = new Date(appointmentBlock.getStart());
Appointment copy = null;
Appointment[] restriction = reservation.getRestriction(oldAllocatable);
boolean includeEvent = restriction.length == 0;
DialogAction result = showDialog(appointmentBlock, "exchange_allocatables", includeEvent, sourceComponent, point);
if (result == DialogAction.CANCEL)
return null;
if (result == DialogAction.SINGLE && appointment.getRepeating() != null) {
copy = copyAppointment(appointment);
copy.setRepeatingEnabled(false);
Calendar cal = getRaplaLocale().createCalendar();
long start = appointment.getStart().getTime();
int hour = DateTools.getHourOfDay(start);
int minute = DateTools.getMinuteOfHour(start);
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY,hour);
cal.set(Calendar.MINUTE, minute);
copy.move(cal.getTime());
}
if (result == DialogAction.EVENT && includeEvent )
{
removeAllocatable = true;
//modifiableReservation.removeAllocatable( oldAllocatable);
if ( reservation.hasAllocated( newAllocatable))
{
newRestrictions.put( newAllocatable, Appointment.EMPTY_ARRAY);
//modifiableReservation.setRestriction( newAllocatable, Appointment.EMPTY_ARRAY);
}
else
{
addAllocatable = true;
//modifiableReservation.addAllocatable(newAllocatable);
}
}
else
{
Appointment[] apps = reservation.getAppointmentsFor(oldAllocatable);
if ( copy != null)
{
exceptionsAdded.add(date);
//Appointment existingAppointment = modifiableReservation.findAppointment( appointment);
//existingAppointment.getRepeating().addException( date );
//modifiableReservation.addAppointment( copy);
addAppointment = copy;
List<Allocatable> all =new ArrayList<Allocatable>(Arrays.asList(reservation.getAllocatablesFor(appointment)));
all.remove(oldAllocatable);
for ( Allocatable a:all)
{
Appointment[] restr = reservation.getRestriction( a);
if ( restr.length > 0)
{
List<Appointment> restrictions = new ArrayList<Appointment>( Arrays.asList( restr));
restrictions.add( copy );
newRestrictions.put(a, restrictions.toArray(Appointment.EMPTY_ARRAY));
//reservation.setRestriction(a, newRestrictions.toArray(new Appointment[] {}));
}
}
newRestrictions.put( oldAllocatable, apps);
//modifiableReservation.setRestriction(oldAllocatable,apps);
}
else
{
if ( apps.length == 1)
{
//modifiableReservation.removeAllocatable(oldAllocatable);
removeAllocatable = true;
}
else
{
List<Appointment> appointments = new ArrayList<Appointment>(Arrays.asList( apps));
appointments.remove( appointment);
newRestrictions.put(oldAllocatable , appointments.toArray(Appointment.EMPTY_ARRAY));
//modifiableReservation.setRestriction(oldAllocatable, appointments.toArray(Appointment.EMPTY_ARRAY));
}
}
Appointment app;
if ( copy != null)
{
app = copy;
}
else
{
app = appointment;
}
if ( reservation.hasAllocated( newAllocatable))
{
Appointment[] existingRestrictions =reservation.getRestriction(newAllocatable);
Collection<Appointment> restrictions = new LinkedHashSet<Appointment>( Arrays.asList(existingRestrictions));
if ( existingRestrictions.length ==0 || restrictions.contains( app))
{
// is already allocated, do nothing
}
else
{
restrictions.add(app);
}
newRestrictions.put( newAllocatable, restrictions.toArray(Appointment.EMPTY_ARRAY));
//modifiableReservation.setRestriction(newAllocatable, newRestrictions.toArray(Appointment.EMPTY_ARRAY));
}
else
{
addAllocatable = true;
//modifiableReservation.addAllocatable( newAllocatable);
if ( reservation.getAppointments().length > 1 || addAppointment != null)
{
newRestrictions.put( newAllocatable,new Appointment[] {app});
//modifiableReservation.setRestriction(newAllocatable, new Appointment[] {appointment});
}
}
}
if ( newStart != null)
{
long offset = newStart.getTime() - appointmentBlock.getStart();
Appointment app= addAppointment != null ? addAppointment : appointment;
newStart = new Date( app.getStart().getTime()+ offset);
}
AllocatableExchangeCommand command = new AllocatableExchangeCommand( appointment, oldAllocatable, newAllocatable,newStart, newRestrictions, removeAllocatable, addAllocatable, addAppointment, exceptionsAdded, sourceComponent);
return command;
}
class AllocatableExchangeCommand implements CommandUndo<RaplaException>
{
Appointment appointment;
Allocatable oldAllocatable;
Allocatable newAllocatable;
Map<Allocatable, Appointment[]> newRestrictions;
Map<Allocatable, Appointment[]> oldRestrictions;
boolean removeAllocatable;
boolean addAllocatable;
Appointment addAppointment;
List<Date> exceptionsAdded;
Date newStart;
boolean firstTimeCall = true;
Component sourceComponent;
AllocatableExchangeCommand(Appointment appointment, Allocatable oldAllocatable, Allocatable newAllocatable, Date newStart,Map<Allocatable, Appointment[]> newRestrictions, boolean removeAllocatable, boolean addAllocatable, Appointment addAppointment,
List<Date> exceptionsAdded, Component sourceComponent)
{
this.appointment = appointment;
this.oldAllocatable = oldAllocatable;
this.newAllocatable = newAllocatable;
this.newStart = newStart;
this.newRestrictions = newRestrictions;
this.removeAllocatable = removeAllocatable;
this.addAllocatable = addAllocatable;
this.addAppointment = addAppointment;
this.exceptionsAdded = exceptionsAdded;
this.sourceComponent = sourceComponent;
}
public boolean execute() throws RaplaException
{
Reservation modifiableReservation = getModifiedReservationForExecute();
if ( firstTimeCall)
{
firstTimeCall = false;
return save(modifiableReservation, sourceComponent);
}
else
{
getModification().store( modifiableReservation );
return true;
}
}
protected Reservation getModifiedReservationForExecute() throws RaplaException {
Reservation reservation = appointment.getReservation();
Reservation modifiableReservation = getModification().edit(reservation);
if ( addAppointment != null)
{
modifiableReservation.addAppointment( addAppointment);
}
Appointment existingAppointment = modifiableReservation.findAppointment( appointment);
if ( existingAppointment != null)
{
for ( Date exception: exceptionsAdded)
{
existingAppointment.getRepeating().addException( exception );
}
}
if ( removeAllocatable)
{
modifiableReservation.removeAllocatable( oldAllocatable);
}
if ( addAllocatable)
{
modifiableReservation.addAllocatable(newAllocatable);
}
oldRestrictions = new HashMap<Allocatable, Appointment[]>();
for ( Allocatable alloc: reservation.getAllocatables())
{
oldRestrictions.put( alloc, reservation.getRestriction( alloc));
}
for ( Allocatable alloc: newRestrictions.keySet())
{
Appointment[] restrictions = newRestrictions.get( alloc);
ArrayList<Appointment> foundAppointments = new ArrayList<Appointment>();
for ( Appointment app: restrictions)
{
Appointment found = modifiableReservation.findAppointment( app);
if ( found != null)
{
foundAppointments.add( found);
}
}
modifiableReservation.setRestriction(alloc, foundAppointments.toArray( Appointment.EMPTY_ARRAY));
}
if ( newStart != null)
{
if ( addAppointment != null)
{
addAppointment.move( newStart);
}
else if (existingAppointment != null)
{
existingAppointment.move( newStart);
}
}
// long startTime = (dialogResult == DialogAction.SINGLE) ? sourceStart.getTime() : ap.getStart().getTime();
//
// changeStart = new Date(startTime + offset);
//
// if (resizing) {
// changeEnd = new Date(changeStart.getTime() + (destEnd.getTime() - destStart.getTime()));
// ap.move(changeStart, changeEnd);
// } else {
// ap.move(changeStart);
// }
return modifiableReservation;
}
public boolean undo() throws RaplaException
{
Reservation modifiableReservation = getModifiedReservationForUndo();
getModification().store( modifiableReservation);
return true;
}
protected Reservation getModifiedReservationForUndo()
throws RaplaException {
Reservation persistant = getModification().getPersistant(appointment.getReservation());
Reservation modifiableReservation = getModification().edit(persistant);
if ( addAppointment != null)
{
Appointment found = modifiableReservation.findAppointment( addAppointment );
if ( found != null)
{
modifiableReservation.removeAppointment( found );
}
}
Appointment existingAppointment = modifiableReservation.findAppointment( appointment);
if ( existingAppointment != null)
{
for ( Date exception: exceptionsAdded)
{
existingAppointment.getRepeating().removeException( exception );
}
if ( newStart != null)
{
Date oldStart = appointment.getStart();
existingAppointment.move( oldStart);
}
}
if ( removeAllocatable)
{
modifiableReservation.addAllocatable( oldAllocatable);
}
if ( addAllocatable)
{
modifiableReservation.removeAllocatable(newAllocatable);
}
for ( Allocatable alloc: oldRestrictions.keySet())
{
Appointment[] restrictions = oldRestrictions.get( alloc);
ArrayList<Appointment> foundAppointments = new ArrayList<Appointment>();
for ( Appointment app: restrictions)
{
Appointment found = modifiableReservation.findAppointment( app);
if ( found != null)
{
foundAppointments.add( found);
}
}
modifiableReservation.setRestriction(alloc, foundAppointments.toArray( Appointment.EMPTY_ARRAY));
}
return modifiableReservation;
}
public String getCommandoName()
{
return getString("exchange_allocatables");
}
}
/**
* This class collects any information of an appointment that is resized or moved in any way
* in the calendar view.
* This is where undo/redo for moving or resizing of an appointment
* in the calendar view is realized.
* @author Jens Fritz
*
*/
//Erstellt und bearbeitet von Dominik Krickl-Vorreiter und Jens Fritz
class AppointmentResize implements CommandUndo<RaplaException> {
private final Date oldStart;
private final Date oldEnd;
private final Date newStart;
private final Date newEnd;
private final Appointment appointment;
private final Component sourceComponent;
private final DialogAction dialogResult;
private Appointment lastCopy;
private boolean firstTimeCall = true;
private boolean keepTime;
public AppointmentResize(Appointment appointment, Date oldStart, Date oldEnd, Date newStart, Date newEnd, Component sourceComponent, DialogAction dialogResult, boolean keepTime) {
this.oldStart = oldStart;
this.oldEnd = oldEnd;
this.newStart = newStart;
this.newEnd = newEnd;
this.appointment = appointment;
this.sourceComponent = sourceComponent;
this.dialogResult = dialogResult;
this.keepTime = keepTime;
lastCopy = null;
}
public boolean execute() throws RaplaException {
boolean resizing = newEnd != null;
Date sourceStart = oldStart;
Date destStart = newStart;
Date destEnd = newEnd;
return doMove(resizing, sourceStart, destStart, destEnd, false);
}
public boolean undo() throws RaplaException {
boolean resizing = newEnd != null;
Date sourceStart = newStart;
Date destStart = oldStart;
Date destEnd = oldEnd;
return doMove(resizing, sourceStart, destStart, destEnd, true);
}
private boolean doMove(boolean resizing, Date sourceStart,
Date destStart, Date destEnd, boolean undo) throws RaplaException {
Reservation reservation = appointment.getReservation();
Reservation mutableReservation = getModification().edit(reservation);
Appointment mutableAppointment = mutableReservation.findAppointment(appointment);
if (mutableAppointment == null) {
throw new IllegalStateException("Can't find the appointment: " + appointment);
}
long offset = getOffset(sourceStart, destStart, keepTime);
Collection<Appointment> appointments;
// Move the complete serie
switch (dialogResult) {
case SERIE:
// Wir wollen eine Serie (Appointment mit Wdh) verschieben
appointments = Collections.singleton(mutableAppointment);
break;
case EVENT:
// Wir wollen die ganze Reservation verschieben
appointments = Arrays.asList(mutableReservation.getAppointments());
break;
case SINGLE:
// Wir wollen nur ein Appointment aus einer Serie verschieben --> losl_sen von Serie
Repeating repeating = mutableAppointment.getRepeating();
if (repeating == null) {
appointments = Arrays.asList(mutableAppointment);
}
else
{
if (undo)
{
mutableReservation.removeAppointment(lastCopy);
repeating.removeException(oldStart);
lastCopy = null;
return save(mutableReservation, sourceComponent);
}
else
{
lastCopy = copyAppointment(mutableAppointment);
lastCopy.setRepeatingEnabled(false);
appointments = Arrays.asList(lastCopy);
}
}
break;
default:
throw new IllegalStateException("Dialog choice not supported "+ dialogResult ) ;
}
Date changeStart;
Date changeEnd;
for (Appointment ap : appointments) {
long startTime = (dialogResult == DialogAction.SINGLE) ? sourceStart.getTime() : ap.getStart().getTime();
changeStart = new Date(startTime + offset);
if (resizing) {
changeEnd = new Date(changeStart.getTime() + (destEnd.getTime() - destStart.getTime()));
ap.move(changeStart, changeEnd);
} else {
ap.move(changeStart);
}
}
if ( !undo)
{
if (dialogResult == DialogAction.SINGLE) {
Repeating repeating = mutableAppointment.getRepeating();
if (repeating != null) {
Allocatable[] restrictedAllocatables = mutableReservation.getRestrictedAllocatables(mutableAppointment);
mutableReservation.addAppointment(lastCopy);
mutableReservation.setRestriction(lastCopy, restrictedAllocatables);
repeating.addException(oldStart);
}
}
}
if ( firstTimeCall)
{
firstTimeCall = false;
return save(mutableReservation, sourceComponent);
}
else
{
getModification().store( mutableReservation );
return true;
}
}
public String getCommandoName() {
return getString("move");
}
}
/**
* This class collects any information of an appointment that is copied and pasted
* in the calendar view.
* This is where undo/redo for pasting an appointment
* in the calendar view is realized.
* @author Jens Fritz
*
*/
//Erstellt von Dominik Krickl-Vorreiter
class AppointmentPaste implements CommandUndo<RaplaException> {
private final Appointment fromAppointment;
private final Reservation fromReservation;
private final Allocatable[] restrictedAllocatables;
private final boolean asNewReservation;
private final boolean copyWholeReservation;
private final long offset;
private final Component sourceComponent;
private Reservation saveReservation = null;
private Appointment saveAppointment = null;
private boolean firstTimeCall = true;
public AppointmentPaste(Appointment fromAppointment, Reservation fromReservation, Allocatable[] restrictedAllocatables, boolean asNewReservation, boolean copyWholeReservation, long offset, Component sourceComponent) {
this.fromAppointment = fromAppointment;
this.fromReservation = fromReservation;
this.restrictedAllocatables = restrictedAllocatables;
this.asNewReservation = asNewReservation;
this.copyWholeReservation = copyWholeReservation;
this.offset = offset;
this.sourceComponent = sourceComponent;
assert !(!asNewReservation && copyWholeReservation);
}
public boolean execute() throws RaplaException {
Reservation mutableReservation = null;
if (asNewReservation) {
if (saveReservation == null) {
mutableReservation = getModification().clone(fromReservation);
} else {
mutableReservation = saveReservation;
}
// Alle anderen Appointments verschieben / entfernen
Appointment[] appointments = mutableReservation.getAppointments();
for (int i=0; i < appointments.length; i++) {
Appointment app = appointments[i];
if (copyWholeReservation) {
if (saveReservation == null) {
app.move(new Date(app.getStart().getTime() + offset));
}
} else {
mutableReservation.removeAppointment(app);
}
}
} else {
mutableReservation = getModification().edit(fromReservation);
}
if (!copyWholeReservation) {
if (saveAppointment == null) {
saveAppointment = copyAppointment(fromAppointment);
saveAppointment.move(new Date(saveAppointment.getStart().getTime() + offset));
}
mutableReservation.addAppointment(saveAppointment);
mutableReservation.setRestriction(saveAppointment, restrictedAllocatables);
}
saveReservation = mutableReservation;
if ( firstTimeCall)
{
firstTimeCall = false;
return save(mutableReservation, sourceComponent);
}
else
{
getModification().store( mutableReservation );
return true;
}
}
public boolean undo() throws RaplaException {
if (asNewReservation) {
Reservation mutableReservation = getModification().edit(saveReservation);
getModification().remove(mutableReservation);
return true;
} else {
Reservation mutableReservation = getModification().edit(saveReservation);
mutableReservation.removeAppointment(saveAppointment);
getModification().store(mutableReservation);
return true;
}
}
public String getCommandoName()
{
return getString("paste");
}
}
class ReservationPaste implements CommandUndo<RaplaException> {
private final Collection<Reservation> fromReservation;
Date start;
Reservation[] array;
public ReservationPaste(Collection<Reservation> fromReservation,Date start) {
this.fromReservation = fromReservation;
this.start = start;
}
public boolean execute() throws RaplaException {
List<Reservation> clones = copy(fromReservation,start);
array = clones.toArray(Reservation.RESERVATION_ARRAY);
getModification().storeAndRemove(array , Reservation.RESERVATION_ARRAY);
return true;
}
public boolean undo() throws RaplaException {
getModification().storeAndRemove(Reservation.RESERVATION_ARRAY,array );
return true;
}
public String getCommandoName()
{
return getString("paste");
}
}
/**
* This class collects any information of an appointment that is saved
* to the calendar view.
* This is where undo/redo for saving an appointment
* in the calendar view is realized.
* @author Jens Fritz
*
*/
//Erstellt von Dominik Krickl-Vorreiter
class ReservationSave extends SaveUndo<Reservation> {
private final Component sourceComponent;
Reservation newReservation;
public ReservationSave(Reservation newReservation, Reservation original, Component sourceComponent)
{
super(ReservationControllerImpl.this.getContext(),Collections.singletonList(newReservation), original != null ? Collections.singletonList(original): null);
this.sourceComponent = sourceComponent;
this.newReservation = newReservation;
}
public boolean execute() throws RaplaException
{
if ( firstTimeCall)
{
firstTimeCall = false;
return save(newReservation, sourceComponent, new SaveCommand(newReservation));
}
else
{
return super.execute();
}
}
}
}
| 04900db4-rob | src/org/rapla/gui/internal/edit/reservation/ReservationControllerImpl.java | Java | gpl3 | 57,013 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.edit.reservation;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.JLabel;
import org.rapla.gui.toolkit.AWTColorUtil;
import org.rapla.gui.toolkit.RaplaColors;
/** A label with a background-color corresponding to the index
of the appointment.
@see RaplaColors#getAppointmentColor
*/
public class AppointmentIdentifier extends JLabel {
private static final long serialVersionUID = 1L;
String text;
int index = 0;
public void setIndex(int index) {
this.index = index;
}
public void setText(String text) {
this.text = text;
super.setText(text + " ");
}
public void paintComponent(Graphics g) {
FontMetrics fm = g.getFontMetrics();
Insets insets = getInsets();
String s = text;
int width = fm.stringWidth(s);
int x = 1;
g.setColor(AWTColorUtil.getAppointmentColor(index));
g.fillRoundRect(x
,insets.top
,width +1
,getHeight()-insets.top -insets.bottom-1,4,4);
g.setColor(getForeground());
g.drawRoundRect(x-1
,insets.top
,width +2
,getHeight()-insets.top -insets.bottom-1,4,4);
g.drawString(s
,x
,getHeight() /2 + fm.getDescent() + 1);
}
}
| 04900db4-rob | src/org/rapla/gui/internal/edit/reservation/AppointmentIdentifier.java | Java | gpl3 | 2,156 |
/*--------------------------------------------------------------------------*
| Copyright (C) 2014 Christopher Kohlhaas |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by the |
| Free Software Foundation. A copy of the license has been included with |
| these distribution in the COPYING file, if not go to www.fsf.org |
| |
| As a special exception, you are granted the permissions to link this |
| program with every library, which license fulfills the Open Source |
| Definition as published by the Open Source Initiative (OSI). |
*--------------------------------------------------------------------------*/
package org.rapla.gui.internal.edit.reservation;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.EventObject;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.swing.AbstractAction;
import javax.swing.DefaultCellEditor;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComponent;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.MenuSelectionManager;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.EventListenerList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.plaf.basic.BasicCheckBoxMenuItemUI;
import javax.swing.plaf.basic.BasicRadioButtonMenuItemUI;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import org.rapla.components.layout.TableLayout;
import org.rapla.components.treetable.AbstractTreeTableModel;
import org.rapla.components.treetable.JTreeTable;
import org.rapla.components.treetable.TableToolTipRenderer;
import org.rapla.components.treetable.TreeTableModel;
import org.rapla.components.util.undo.CommandHistory;
import org.rapla.components.util.undo.CommandUndo;
import org.rapla.entities.Named;
import org.rapla.entities.User;
import org.rapla.entities.domain.Allocatable;
import org.rapla.entities.domain.Appointment;
import org.rapla.entities.domain.AppointmentStartComparator;
import org.rapla.entities.domain.Reservation;
import org.rapla.entities.domain.ResourceAnnotations;
import org.rapla.entities.dynamictype.Classification;
import org.rapla.entities.dynamictype.ClassificationFilter;
import org.rapla.entities.dynamictype.DynamicType;
import org.rapla.entities.dynamictype.DynamicTypeAnnotations;
import org.rapla.facade.CalendarModel;
import org.rapla.facade.CalendarSelectionModel;
import org.rapla.facade.ModificationEvent;
import org.rapla.facade.RaplaComponent;
import org.rapla.facade.internal.FacadeImpl;
import org.rapla.framework.RaplaContext;
import org.rapla.framework.RaplaException;
import org.rapla.gui.AppointmentListener;
import org.rapla.gui.MenuContext;
import org.rapla.gui.MenuFactory;
import org.rapla.gui.RaplaGUIComponent;
import org.rapla.gui.TreeFactory;
import org.rapla.gui.internal.FilterEditButton;
import org.rapla.gui.internal.MenuFactoryImpl;
import org.rapla.gui.internal.common.CalendarAction;
import org.rapla.gui.internal.edit.ClassifiableFilterEdit;
import org.rapla.gui.toolkit.AWTColorUtil;
import org.rapla.gui.toolkit.PopupEvent;
import org.rapla.gui.toolkit.PopupListener;
import org.rapla.gui.toolkit.RaplaButton;
import org.rapla.gui.toolkit.RaplaMenu;
import org.rapla.gui.toolkit.RaplaPopupMenu;
import org.rapla.gui.toolkit.RaplaSeparator;
import org.rapla.gui.toolkit.RaplaWidget;
/**
* <p>
* GUI for editing the allocations of a reservation. Presents two TreeTables. The left one displays
* all available Resources and Persons the right one all selected Resources and Persons.
* </p>
* <p>
* The second column of the first table contains information about the availability on the
* appointments of the reservation. In the second column of the second table the user can add
* special Restrictions on the selected Resources and Persons.
* </p>
*
* @see Reservation
* @see Allocatable
*/
public class AllocatableSelection extends RaplaGUIComponent implements AppointmentListener, PopupListener, RaplaWidget
{
JSplitPane content = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
JPanel leftPanel = new JPanel();
JTreeTable completeTable;
RaplaButton btnAdd = new RaplaButton(RaplaButton.SMALL);
RaplaButton btnCalendar1 = new RaplaButton(RaplaButton.SMALL);
JPanel rightPanel = new JPanel();
JTreeTable selectedTable;
RaplaButton btnRemove = new RaplaButton(RaplaButton.SMALL);
RaplaButton btnCalendar2 = new RaplaButton(RaplaButton.SMALL);
Reservation mutableReservation;
Reservation originalReservation;
AllocatablesModel completeModel = new CompleteModel();
AllocatablesModel selectedModel = new SelectedModel();
Map<Allocatable, Collection<Appointment>> allocatableBindings = new HashMap<Allocatable, Collection<Appointment>>();
// Map<Appointment,Collection<Allocatable>> appointmentMap = new HashMap<Appointment,Collection<Allocatable>>();
Appointment[] appointments;
String[] appointmentStrings;
String[] appointmentIndexStrings;
CalendarSelectionModel calendarModel;
EventListenerList listenerList = new EventListenerList();
Listener listener = new Listener();
//FilterAction filterAction;
AllocatableAction addAction;
AllocatableAction removeAction;
AllocatableAction calendarAction1;
AllocatableAction calendarAction2;
User user;
CommandHistory commandHistory;
FilterEditButton filter;
public AllocatableSelection(RaplaContext sm)
{
this(sm, false, new CommandHistory());
}
public AllocatableSelection(RaplaContext sm, boolean addCalendarButton,CommandHistory commandHistory)
{
super(sm);
// Undo Command History
this.commandHistory = commandHistory;
double pre = TableLayout.PREFERRED;
double fill = TableLayout.FILL;
double tableSize[][] = { { pre, 12, pre, 3, fill, pre}, // Columns
{ pre, fill } }; // Rows
leftPanel.setLayout(new TableLayout(tableSize));
if (addCalendarButton)
leftPanel.add(btnCalendar1, "0,0,l,f");
leftPanel.add(btnAdd, "5,0,r,f");
rightPanel.setLayout(new TableLayout(tableSize));
rightPanel.add(btnRemove, "0,0,l,f");
if (addCalendarButton)
rightPanel.add(btnCalendar2, "2,0,c,c");
content.setLeftComponent(leftPanel);
content.setRightComponent(rightPanel);
content.setResizeWeight(0.3);
btnAdd.setEnabled(false);
btnCalendar1.setEnabled(false);
btnRemove.setEnabled(false);
btnCalendar2.setEnabled(false);
addAction = new AllocatableAction("add");
removeAction = new AllocatableAction("remove");
calendarAction1 = new AllocatableAction("calendar1");
calendarAction2 = new AllocatableAction("calendar2");
btnAdd.setAction(addAction);
btnRemove.setAction(removeAction);
btnCalendar1.setAction(calendarAction1);
btnCalendar2.setAction(calendarAction2);
completeTable = new JTreeTable(completeModel);
Color tableBackground = completeTable.getTree().getBackground();
JScrollPane leftScrollpane = new JScrollPane(completeTable);
leftScrollpane.getViewport().setBackground(tableBackground);
leftPanel.add(leftScrollpane, "0,1,5,1,f,f");
completeTable.setGridColor(darken(tableBackground, 20));
completeTable.setToolTipRenderer(new RaplaToolTipRenderer());
completeTable.getSelectionModel().addListSelectionListener(listener);
completeTable.setDefaultRenderer(Allocatable.class, new AllocationCellRenderer());
completeTable.setDefaultEditor(Allocatable.class, new AppointmentCellEditor2(new AllocationTextField()));
completeTable.getTree().setCellRenderer(new AllocationTreeCellRenderer(false));
completeTable.addMouseListener(listener);
selectedTable = new JTreeTable(selectedModel);
JScrollPane rightScrollpane = new JScrollPane(selectedTable);
rightScrollpane.getViewport().setBackground(tableBackground);
rightPanel.add(rightScrollpane, "0,1,5,1,f,f");
selectedTable.setToolTipRenderer(new RaplaToolTipRenderer());
selectedTable.getSelectionModel().addListSelectionListener(listener);
selectedTable.setGridColor(darken(tableBackground, 20));
selectedTable.setDefaultRenderer(Appointment[].class, new RestrictionCellRenderer());
AppointmentCellEditor appointmentCellEditor = new AppointmentCellEditor(new RestrictionTextField());
selectedTable.setDefaultEditor(Appointment[].class, appointmentCellEditor);
selectedTable.addMouseListener(listener);
selectedTable.getTree().setCellRenderer(new AllocationTreeCellRenderer(true));
completeTable.getColumnModel().getColumn(0).setMinWidth(60);
completeTable.getColumnModel().getColumn(0).setPreferredWidth(120);
completeTable.getColumnModel().getColumn(1).sizeWidthToFit();
selectedTable.getColumnModel().getColumn(0).setMinWidth(60);
selectedTable.getColumnModel().getColumn(0).setPreferredWidth(120);
selectedTable.getColumnModel().getColumn(1).sizeWidthToFit();
content.setDividerLocation(0.3);
CalendarSelectionModel originalModel = getService(CalendarSelectionModel.class);
calendarModel = originalModel.clone();
filter = new FilterEditButton( sm, calendarModel, listener,true);
leftPanel.add(filter.getButton(), "4,0,r,f");
// filterAction = new FilterAction(getContext(), getComponent(), null);
// filterAction.setFilter(calendarModel);
// filterAction.setResourceOnly(true);
}
public void addChangeListener(ChangeListener listener)
{
listenerList.add(ChangeListener.class, listener);
}
public void removeChangeListener(ChangeListener listener)
{
listenerList.remove(ChangeListener.class, listener);
}
final private TreeFactory getTreeFactory()
{
return getService(TreeFactory.class);
}
protected void fireAllocationsChanged()
{
ChangeEvent evt = new ChangeEvent(this);
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2)
{
if (listeners[i] == ChangeListener.class)
{
((ChangeListener) listeners[i + 1]).stateChanged(evt);
}
}
}
public void dataChanged(ModificationEvent evt) throws RaplaException
{
calendarModel.dataChanged( evt);
boolean updateBindings = false;
if (evt.isModified(Allocatable.TYPE))
{
updateBindings = true;
Collection<Allocatable> allAllocatables = getAllAllocatables();
completeModel.setAllocatables(allAllocatables, completeTable.getTree());
for ( Allocatable allocatable:selectedModel.getAllocatables())
{
if ( !allAllocatables.contains(allocatable ))
{
mutableReservation.removeAllocatable( allocatable);
}
}
selectedModel.setAllocatables(Arrays.asList(mutableReservation.getAllocatables()), selectedTable.getTree());
updateButtons();
}
if (updateBindings || evt.isModified(Reservation.TYPE))
{
updateBindings(null);
}
}
/** Implementation of appointment listener */
public void appointmentAdded(Collection<Appointment> appointments)
{
setAppointments(mutableReservation.getAppointments());
selectedModel.setAllocatables(getAllocated(), selectedTable.getTree());
updateBindings( appointments);
}
public void appointmentChanged(Collection<Appointment> appointments)
{
setAppointments(mutableReservation.getAppointments());
updateBindings( appointments );
}
public void appointmentRemoved(Collection<Appointment> appointments)
{
removeFromBindings( appointments);
setAppointments(mutableReservation.getAppointments());
selectedModel.setAllocatables(getAllocated(), selectedTable.getTree());
removeFromBindings( appointments);
List<Appointment> emptyList = Collections.emptyList();
updateBindings(emptyList);
}
public void appointmentSelected(Collection<Appointment> appointments)
{
}
private void updateBindings(Collection<Appointment> appointments)
{
Collection<Allocatable> allAllocatables = new LinkedHashSet<Allocatable>( completeModel.getAllocatables());
allAllocatables.addAll(Arrays.asList( mutableReservation.getAllocatables()));
if ( appointments == null)
{
allocatableBindings.clear();
for ( Allocatable allocatable: allAllocatables)
{
allocatableBindings.put( allocatable, new HashSet<Appointment>());
}
appointments = Arrays.asList(mutableReservation.getAppointments());
}
try
{
if (!RaplaComponent.isTemplate( this.mutableReservation))
{
// System.out.println("getting allocated resources");
Map<Allocatable, Collection<Appointment>> allocatableBindings = getQuery().getAllocatableBindings(allAllocatables,appointments);
removeFromBindings( appointments);
for ( Map.Entry<Allocatable, Collection<Appointment>> entry: allocatableBindings.entrySet())
{
Allocatable alloc = entry.getKey();
Collection<Appointment> list = this.allocatableBindings.get( alloc);
if ( list == null)
{
list = new HashSet<Appointment>();
this.allocatableBindings.put( alloc, list);
}
Collection<Appointment> bindings = entry.getValue();
list.addAll( bindings);
}
}
//this.allocatableBindings.putAll(allocatableBindings);
completeModel.treeDidChange();
selectedModel.treeDidChange();
}
catch (RaplaException ex)
{
showException(ex, content);
}
}
private void removeFromBindings(Collection<Appointment> appointments) {
for ( Collection<Appointment> list: allocatableBindings.values())
{
for ( Appointment app:appointments)
{
list.remove(app);
}
}
}
public JComponent getComponent()
{
return content;
}
private Set<Allocatable> getAllAllocatables() throws RaplaException
{
Allocatable[] allocatables = getQuery().getAllocatables(calendarModel.getAllocatableFilter());
Set<Allocatable> rightsToAllocate = new HashSet<Allocatable>();
Date today = getQuery().today();
for (Allocatable alloc:allocatables)
{
if (alloc.canAllocate(user, today))
{
rightsToAllocate.add( alloc );
}
}
return rightsToAllocate;
}
private Set<Allocatable> getAllocated()
{
Allocatable[] allocatables = mutableReservation.getAllocatables();
Set<Allocatable> result = new HashSet<Allocatable>(Arrays.asList(allocatables));
return result;
}
private boolean bWorkaround = false; // Workaround for Bug ID 4480264 on developer.java.sun.com
public void setReservation(Reservation mutableReservation, Reservation originalReservation) throws RaplaException
{
this.originalReservation = originalReservation;
this.mutableReservation = mutableReservation;
this.user = getUser();
setAppointments(mutableReservation.getAppointments());
Collection<Allocatable> allocatableList = getAllAllocatables();
completeModel.setAllocatables(allocatableList);
updateBindings( null);
// Expand allocatableTree if only one DynamicType
final CalendarModel calendarModel = getService(CalendarModel.class);
Collection<?> selectedObjectsAndChildren = calendarModel.getSelectedObjects();
expandObjects(selectedObjectsAndChildren, completeTable.getTree());
selectedModel.setAllocatables(getAllocated(), selectedTable.getTree());
expandObjects( getAllocated(), selectedTable.getTree());
updateButtons();
JTree tree = selectedTable.getTree();
for (int i = 0; i < tree.getRowCount(); i++)
tree.expandRow(i);
// Workaround for Bug ID 4480264 on developer.java.sun.com
bWorkaround = true;
if (selectedTable.getRowCount() > 0)
{
selectedTable.editCellAt(1, 1);
selectedTable.editCellAt(1, 0);
}
bWorkaround = false;
//filterAction.removePropertyChangeListener(listener);
// filterAction.addPropertyChangeListener(listener);
// btnFilter.setAction(filterAction);
// We have to add this after processing, because the Adapter in the JTreeTable does the same
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
selectObjects(calendarModel.getSelectedObjects(), completeTable.getTree());
}
});
}
private void setAppointments(Appointment[] appointmentArray)
{
List<Appointment> sortedAppointments = new ArrayList<Appointment>( Arrays.asList( appointmentArray));
Collections.sort(sortedAppointments, new AppointmentStartComparator() );
this.appointments = sortedAppointments.toArray( Appointment.EMPTY_ARRAY);
this.appointmentStrings = new String[appointments.length];
this.appointmentIndexStrings = new String[appointments.length];
for (int i = 0; i < appointments.length; i++)
{
this.appointmentStrings[i] = getAppointmentFormater().getVeryShortSummary(appointments[i]);
this.appointmentIndexStrings[i] = getRaplaLocale().formatNumber(i + 1);
}
}
private boolean isAllocatableSelected(JTreeTable table)
{
// allow folders to be selected
return isElementSelected(table, false);
}
private boolean isElementSelected(JTreeTable table, boolean allocatablesOnly)
{
int start = table.getSelectionModel().getMinSelectionIndex();
int end = table.getSelectionModel().getMaxSelectionIndex();
if (start >= 0)
{
for (int i = start; i <= end; i++)
{
TreePath path = table.getTree().getPathForRow(i);
if (path != null && (!allocatablesOnly || ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject() instanceof Allocatable))
return true;
}
}
return false;
}
public Set<Allocatable> getMarkedAllocatables()
{
return new HashSet<Allocatable>(getSelectedAllocatables(completeTable.getTree()));
}
protected Collection<Allocatable> getSelectedAllocatables(JTree tree)
{
// allow folders to be selected
Collection<?> selectedElementsIncludingChildren = getSelectedElementsIncludingChildren(tree);
List<Allocatable> allocatables = new ArrayList<Allocatable>();
for (Object obj:selectedElementsIncludingChildren)
{
if ( obj instanceof Allocatable)
{
allocatables.add(( Allocatable) obj);
}
}
return allocatables;
}
protected Collection<?> getSelectedElementsIncludingChildren(JTree tree)
{
TreePath[] paths = tree.getSelectionPaths();
List<Object> list = new LinkedList<Object>();
if ( paths == null)
{
return list;
}
for (TreePath p:paths)
{
DefaultMutableTreeNode node = (DefaultMutableTreeNode) p.getLastPathComponent();
{
Object obj = node.getUserObject();
if (obj != null )
list.add(obj);
}
Enumeration<?> tt = node.children();
for(;tt.hasMoreElements();)
{
DefaultMutableTreeNode nodeChild = (DefaultMutableTreeNode) tt.nextElement();
Object obj = nodeChild.getUserObject();
if (obj != null )
{
list.add(obj);
}
}
}
return list;
}
protected void remove(Collection<Allocatable> elements)
{
Iterator<Allocatable> it = elements.iterator();
boolean bChanged = false;
while (it.hasNext())
{
Allocatable a = it.next();
if (mutableReservation.hasAllocated(a))
{
mutableReservation.removeAllocatable(a);
bChanged = true;
}
}
if (bChanged)
{
selectedModel.setAllocatables(getAllocated(), selectedTable.getTree());
}
fireAllocationsChanged();
}
protected void add(Collection<Allocatable> elements)
{
Iterator<Allocatable> it = elements.iterator();
boolean bChanged = false;
while (it.hasNext())
{
Allocatable a = it.next();
if (!mutableReservation.hasAllocated(a))
{
mutableReservation.addAllocatable(a);
bChanged = true;
}
}
if (bChanged)
{
selectedModel.setAllocatables(getAllocated(), selectedTable.getTree());
expandObjects(elements, selectedTable.getTree());
}
fireAllocationsChanged();
}
private Date findFirstStart(Collection<Appointment> appointments)
{
Date firstStart = null;
for (Appointment app: appointments)
if (firstStart == null || app.getStart().before(firstStart))
firstStart = app.getStart();
return firstStart;
}
private void updateButtons()
{
{
boolean enable = isElementSelected(completeTable, false);
calendarAction1.setEnabled(enable);
enable = enable && isAllocatableSelected(completeTable);
addAction.setEnabled(enable);
}
{
boolean enable = isElementSelected(selectedTable, false);
calendarAction2.setEnabled(enable);
enable = enable && isAllocatableSelected(selectedTable);
removeAction.setEnabled(enable);
}
}
class Listener extends MouseAdapter implements ListSelectionListener, ChangeListener
{
public void valueChanged(ListSelectionEvent e)
{
updateButtons();
}
public void mousePressed(MouseEvent me)
{
if (me.isPopupTrigger())
firePopup(me);
}
public void mouseReleased(MouseEvent me)
{
if (me.isPopupTrigger())
firePopup(me);
}
public void mouseClicked(MouseEvent evt)
{
if (evt.getClickCount() < 2)
return;
JTreeTable table = (JTreeTable) evt.getSource();
int row = table.rowAtPoint(new Point(evt.getX(), evt.getY()));
if (row < 0)
return;
Object obj = table.getValueAt(row, 0);
if (!(obj instanceof Allocatable))
return;
AllocatableChange commando;
if (table == completeTable)
commando = newAllocatableChange("add",completeTable);
else
commando = newAllocatableChange("remove",selectedTable);
commandHistory.storeAndExecute(commando);
}
public void stateChanged(ChangeEvent e) {
try {
ClassifiableFilterEdit filterUI = filter.getFilterUI();
if ( filterUI != null)
{
final ClassificationFilter[] filters = filterUI.getFilters();
calendarModel.setAllocatableFilter( filters);
completeModel.setAllocatables(getAllAllocatables(), completeTable.getTree());
//List<Appointment> appointments = Arrays.asList(mutableReservation.getAppointments());
// it is important to update all bindings, because a
updateBindings( null );
}
} catch (Exception ex) {
showException(ex, getComponent());
}
}
}
protected void firePopup(MouseEvent me)
{
Point p = new Point(me.getX(), me.getY());
JTreeTable table = ((JTreeTable) me.getSource());
int row = table.rowAtPoint(p);
int column = table.columnAtPoint(p);
Object selectedObject = null;
if (row >= 0 && column >= 0)
selectedObject = table.getValueAt(row, column);
//System.out.println("row " + row + " column " + column + " selected " + selectedObject);
showPopup(new PopupEvent(table, selectedObject, p));
}
public void showPopup(PopupEvent evt)
{
try
{
Point p = evt.getPoint();
Object selectedObject = evt.getSelectedObject();
JTreeTable table = ((JTreeTable) evt.getSource());
RaplaPopupMenu menu = new RaplaPopupMenu();
if (table == completeTable)
{
menu.add(new JMenuItem(addAction));
menu.add(new JMenuItem(calendarAction1));
}
else
{
menu.add(new JMenuItem(removeAction));
menu.add(new JMenuItem(calendarAction2));
}
String seperatorId = "ADD_REMOVE_SEPERATOR";
menu.add( new RaplaSeparator(seperatorId));
MenuContext menuContext = createMenuContext(p, selectedObject);
Collection<?> list = getSelectedAllocatables( table.getTree());
menuContext.setSelectedObjects(list);
RaplaMenu newMenu = new RaplaMenu("new");
newMenu.setText(getString("new"));
MenuFactory menuFactory = getService( MenuFactory.class);
((MenuFactoryImpl) menuFactory).addNew(newMenu, menuContext, null);
menuFactory.addObjectMenu(menu, menuContext, seperatorId);
newMenu.setEnabled( newMenu.getMenuComponentCount() > 0);
menu.insertAfterId(newMenu, seperatorId);
menu.show(table, p.x, p.y);
}
catch (RaplaException ex)
{
showException(ex, getComponent());
}
}
protected MenuContext createMenuContext(Point p, Object obj) {
MenuContext menuContext = new MenuContext(getContext(), obj, getComponent(), p);
return menuContext;
}
public void expandObjects(Collection<? extends Object> expandedNodes, JTree tree)
{
Set<Object> expandedObjects = new LinkedHashSet<Object>();
expandedObjects.addAll( expandedNodes);
// we need an enumeration, because we modife the set
Enumeration<?> enumeration = ((DefaultMutableTreeNode) tree.getModel().getRoot()).preorderEnumeration();
while (enumeration.hasMoreElements())
{
DefaultMutableTreeNode node = (DefaultMutableTreeNode) enumeration.nextElement();
Object userObject = node.getUserObject();
if (expandedObjects.contains(userObject))
{
expandedObjects.remove( userObject );
TreePath path = new TreePath(node.getPath());
while ( path != null)
{
tree.expandPath(path);
path = path.getParentPath();
}
}
}
}
static public void selectObjects(Collection<?> expandedNodes, JTree tree)
{
Enumeration<?> enumeration = ((DefaultMutableTreeNode) tree.getModel().getRoot()).preorderEnumeration();
List<TreePath> selectionPaths = new ArrayList<TreePath>();
Set<Object> alreadySelected = new HashSet<Object>();
while (enumeration.hasMoreElements())
{
DefaultMutableTreeNode node = (DefaultMutableTreeNode) enumeration.nextElement();
Iterator<?> it = expandedNodes.iterator();
while (it.hasNext())
{
Object userObject = node.getUserObject();
if (it.next().equals(userObject) && !alreadySelected.contains( userObject))
{
alreadySelected.add( userObject );
selectionPaths.add(new TreePath(node.getPath()));
}
}
}
tree.setSelectionPaths( selectionPaths.toArray(new TreePath[] {}));
}
class CompleteModel extends AllocatablesModel
{
public int getColumnCount()
{
return 2;
}
public boolean isCellEditable(Object node, int column)
{
return column > 0;
}
public Object getValueAt(Object node, int column)
{
return ((DefaultMutableTreeNode) node).getUserObject();
}
public String getColumnName(int column)
{
switch (column)
{
case 0:
return getString("selectable");
case 1:
return getString("selectable_on");
}
throw new IndexOutOfBoundsException();
}
public Class<?> getColumnClass(int column)
{
switch (column)
{
case 0:
return TreeTableModel.class;
case 1:
return Allocatable.class;
}
throw new IndexOutOfBoundsException();
}
}
class SelectedModel extends AllocatablesModel
{
public SelectedModel() {
super();
useCategorizations = false;
}
public int getColumnCount()
{
return 2;
}
public boolean isCellEditable(Object node, int column)
{
if (column == 1 && bWorkaround)
return true;
Object o = ((DefaultMutableTreeNode) node).getUserObject();
if (column == 1 && o instanceof Allocatable)
return true;
else
return false;
}
public Object getValueAt(Object node, int column)
{
Object o = ((DefaultMutableTreeNode) node).getUserObject();
if (o instanceof Allocatable)
{
switch (column)
{
case 0:
return o;
case 1:
return mutableReservation.getRestriction((Allocatable) o);
}
}
if (o instanceof DynamicType)
{
return o;
}
return o;
//throw new IndexOutOfBoundsException();
}
public void setValueAt(Object value, Object node, int column)
{
Object o = ((DefaultMutableTreeNode) node).getUserObject();
if (column == 1 && o instanceof Allocatable && value instanceof Appointment[])
{
Appointment[] restriction = mutableReservation.getRestriction((Allocatable) o);
Appointment[] newValue = (Appointment[]) value;
if (!Arrays.equals(restriction,newValue))
{
mutableReservation.setRestriction((Allocatable) o, newValue);
fireAllocationsChanged();
}
}
fireTreeNodesChanged(node, ((DefaultMutableTreeNode) node).getPath(), new int[] {}, new Object[] {});
}
public String getColumnName(int column)
{
switch (column)
{
case 0:
return getString("selected");
case 1:
return getString("selected_on");
}
throw new IndexOutOfBoundsException();
}
public Class<?> getColumnClass(int column)
{
switch (column)
{
case 0:
return TreeTableModel.class;
case 1:
return Appointment[].class;
}
throw new IndexOutOfBoundsException();
}
}
abstract class AllocatablesModel extends AbstractTreeTableModel
{
TreeModel treeModel;
boolean useCategorizations;
public AllocatablesModel()
{
super(new DefaultMutableTreeNode());
treeModel = new DefaultTreeModel((DefaultMutableTreeNode) super.getRoot());
useCategorizations = true;
}
// Types of the columns.
Collection<Allocatable> allocatables;
public void setAllocatables(Collection<Allocatable> allocatables)
{
this.allocatables = allocatables;
treeModel = getTreeFactory().createClassifiableModel( allocatables.toArray(Allocatable.ALLOCATABLE_ARRAY), useCategorizations);
DefaultMutableTreeNode root = (DefaultMutableTreeNode) getRoot();
int childCount = root.getChildCount();
int[] childIndices = new int[childCount];
Object[] children = new Object[childCount];
for (int i = 0; i < childCount; i++)
{
childIndices[i] = i;
children[i] = root.getChildAt(i);
}
fireTreeStructureChanged(root, root.getPath(), childIndices, children);
}
public void setAllocatables(Collection<Allocatable> allocatables, JTree tree)
{
this.allocatables = allocatables;
Collection<Object> expanded = new HashSet<Object>();
for (int i = 0; i < tree.getRowCount(); i++)
{
if (tree.isExpanded(i))
{
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getPathForRow(i).getLastPathComponent();
expanded.add(node.getUserObject());
}
}
setAllocatables(allocatables);
expandNodes(expanded, tree);
}
void expandNodes(Collection<Object> expanded, JTree tree)
{
if (expanded.size() == 0)
return;
Collection<Object> expandedToRemove = new LinkedHashSet<Object>( expanded);
for (int i = 0; i < tree.getRowCount(); i++)
{
DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getPathForRow(i).getLastPathComponent();
Object userObject = node.getUserObject();
if (expandedToRemove.contains(userObject))
{
expandedToRemove.remove( userObject );
tree.expandRow(i);
}
}
}
public Collection<Allocatable> getAllocatables()
{
return allocatables;
}
public void treeDidChange()
{
DefaultMutableTreeNode root = (DefaultMutableTreeNode) getRoot();
int childCount = root.getChildCount();
int[] childIndices = new int[childCount];
Object[] children = new Object[childCount];
for (int i = 0; i < childCount; i++)
{
childIndices[i] = i;
children[i] = root.getChildAt(i);
}
fireTreeNodesChanged(root, root.getPath(), childIndices, children);
}
public Object getRoot()
{
return treeModel.getRoot();
}
public int getChildCount(Object node)
{
return treeModel.getChildCount(node);
}
public Object getChild(Object node, int i)
{
return treeModel.getChild(node, i);
}
}
class RestrictionCellRenderer extends DefaultTableCellRenderer
{
private static final long serialVersionUID = 1L;
Object newValue;
JButton button = new JButton();
public void setValue(Object value)
{
newValue = value;
super.setValue("");
}
public void setBounds(int x, int y, int width, int heigth)
{
super.setBounds(x, y, width, heigth);
button.setBounds(x, y, width, heigth);
}
public void paint(Graphics g)
{
Object value = newValue;
if (value instanceof Appointment[])
{
super.paint(g);
java.awt.Font f = g.getFont();
button.paint(g);
g.setFont(f);
paintRestriction(g, (Appointment[]) value, this);
}
}
}
class AllocationCellRenderer extends DefaultTableCellRenderer
{
private static final long serialVersionUID = 1L;
Object newValue;
public void setValue(Object value)
{
newValue = value;
super.setValue("");
}
public void paint(Graphics g)
{
Object value = newValue;
super.paint(g);
if (value instanceof Allocatable)
{
paintAllocation(g, (Allocatable) value, this);
}
}
}
class RaplaToolTipRenderer implements TableToolTipRenderer
{
public String getToolTipText(JTable table, int row, int column)
{
Object value = table.getValueAt(row, column);
return getInfoFactory().getToolTip(value);
}
}
private int indexOf(Appointment appointment)
{
for (int i = 0; i < appointments.length; i++)
if (appointments[i].equals(appointment))
return i;
return -1;
}
// returns if the user is allowed to allocate the passed allocatable
private boolean isAllowed(Allocatable allocatable, Appointment appointment)
{
Date start = appointment.getStart();
Date end = appointment.getMaxEnd();
Date today = getQuery().today();
return allocatable.canAllocate(user, start, end, today);
}
class AllocationRendering
{
boolean conflictingAppointments[] = new boolean[appointments.length]; // stores the temp conflicting appointments
int conflictCount = 0; // temp value for conflicts
int permissionConflictCount = 0; // temp value for conflicts that are the result of denied permissions
}
// calculates the number of conflicting appointments for this allocatable
private AllocationRendering calcConflictingAppointments(Allocatable allocatable)
{
AllocationRendering result = new AllocationRendering();
String annotation = allocatable.getAnnotation( ResourceAnnotations.KEY_CONFLICT_CREATION, null);
boolean holdBackConflicts = annotation != null && annotation.equals( ResourceAnnotations.VALUE_CONFLICT_CREATION_IGNORE);
for (int i = 0; i < appointments.length; i++)
{
Appointment appointment = appointments[i];
Collection<Appointment> collection = allocatableBindings.get( allocatable);
boolean conflictingAppointments = collection != null && collection.contains( appointment);
result.conflictingAppointments[i] = false;
if ( conflictingAppointments )
{
if ( ! holdBackConflicts)
{
result.conflictingAppointments[i] = true;
result.conflictCount++;
}
}
else if (!isAllowed(allocatable, appointment) )
{
if ( ! holdBackConflicts)
{
result.conflictingAppointments[i] = true;
result.conflictCount++;
}
result.permissionConflictCount++;
}
}
return result;
}
private void paintAllocation(Graphics g, Allocatable allocatable, JComponent c)
{
AllocationRendering a = calcConflictingAppointments(allocatable);
if (appointments.length == 0)
{
}
else if (a.conflictCount == 0)
{
g.setColor(Color.green);
g.drawString(getString("every_appointment"), 2, c.getHeight() - 4);
return;
} /*
* else if (conflictCount == appointments.length) {
* g.setColor(Color.red);
* g.drawString(getString("zero_appointment"),2,c.getHeight()-4);
* return;
* }
*/
int x = 2;
Insets insets = c.getInsets();
FontMetrics fm = g.getFontMetrics();
for (int i = 0; i < appointments.length; i++)
{
if (a.conflictingAppointments[i])
continue;
x = paintApp(c, g, fm, i, insets, x);
}
}
private void paintRestriction(Graphics g, Appointment[] restriction, JComponent c)
{
if (restriction.length == 0)
{
g.drawString(getString("every_appointment"), 2, c.getHeight() - 4);
return;
}
int x = 0;
Insets insets = c.getInsets();
FontMetrics fm = g.getFontMetrics();
int i=0;
for (Appointment app:appointments)
{
for (Appointment res:restriction)
{
if (res.equals(app))
{
x = paintApp(c, g, fm, i, insets, x);
}
}
i++;
}
}
private int paintApp(Component c, Graphics g, FontMetrics fm, int index, Insets insets, int x)
{
int xborder = 4;
int yborder = 1;
int width = fm.stringWidth(appointmentIndexStrings[index]);
x += xborder;
g.setColor(AWTColorUtil.getAppointmentColor(index));
g.fillRoundRect(x, insets.top, width, c.getHeight() - insets.top - insets.bottom - yborder * 2, 4, 4);
g.setColor(c.getForeground());
g.drawRoundRect(x - 1, insets.top, width + 1, c.getHeight() - insets.top - insets.bottom - yborder * 2, 4, 4);
g.drawString(appointmentIndexStrings[index], x, c.getHeight() - yborder - fm.getDescent());
x += width;
x += 2;
int textWidth = fm.stringWidth(appointmentStrings[index]);
g.drawString(appointmentStrings[index], x, c.getHeight() - fm.getDescent());
x += textWidth;
x += xborder;
return x;
}
class RestrictionTextField extends JTextField
{
private static final long serialVersionUID = 1L;
Object newValue;
public void setValue(Object value)
{
newValue = value;
}
public void paint(Graphics g)
{
Object value = newValue;
super.paint(g);
if (value instanceof Appointment[])
{
paintRestriction(g, (Appointment[]) value, this);
}
}
}
class AllocationTextField extends JTextField
{
private static final long serialVersionUID = 1L;
Object newValue;
public void setValue(Object value)
{
newValue = value;
}
public void paint(Graphics g)
{
Object value = newValue;
super.paint(g);
if (value instanceof Allocatable)
{
paintAllocation(g, (Allocatable) value, this);
}
}
}
class AppointmentCellEditor extends DefaultCellEditor implements MouseListener, KeyListener, PopupMenuListener, ActionListener
{
private static final long serialVersionUID = 1L;
JPopupMenu menu = new JPopupMenu();
RestrictionTextField editingComponent;
boolean bStopEditingCalled = false; /*
* We need this variable
* to check if
* stopCellEditing
* was already called.
*/
DefaultMutableTreeNode selectedNode;
int selectedColumn = 0;
Appointment[] restriction;
public AppointmentCellEditor(RestrictionTextField textField)
{
super(textField);
editingComponent = (RestrictionTextField) this.getComponent();
editingComponent.setEditable(false);
editingComponent.addMouseListener(this);
editingComponent.addKeyListener(this);
menu.addPopupMenuListener(this);
}
public void mouseReleased(MouseEvent evt)
{
showComp();
}
public void mousePressed(MouseEvent evt)
{
}
public void mouseClicked(MouseEvent evt)
{
}
public void mouseEntered(MouseEvent evt)
{
}
public void mouseExited(MouseEvent evt)
{
}
public void keyPressed(KeyEvent evt)
{
}
public void keyTyped(KeyEvent evt)
{
}
public void keyReleased(KeyEvent evt)
{
showComp();
}
/**
* This method is performed, if the user clicks on a menu item of the
* <code>JPopupMenu</code> in order to select invividual appointments
* for a resource.
*
* Changed in Rapla 1.4
*/
public void actionPerformed(ActionEvent evt)
{
// Refresh the selected appointments for the resource which is being
// edited
int oldRestrictionLength = restriction.length;
Appointment[] oldRestriction = restriction;
Object selectedObject = selectedNode.getUserObject();
Object source = evt.getSource();
if ( source == selectedMenu)
{
AllocationRendering allocBinding = null;
if (selectedObject instanceof Allocatable)
{
Allocatable allocatable = (Allocatable) selectedObject;
allocBinding = calcConflictingAppointments(allocatable);
}
List<Appointment> newRestrictions = new ArrayList<Appointment>();
for (int i = 0; i < appointments.length; i++)
{
boolean conflicting = (allocBinding != null && allocBinding.conflictingAppointments[i]);
( appointmentList.get(i)).setSelected(!conflicting);
if ( !conflicting)
{
newRestrictions.add(appointments[i]);
}
}
restriction = newRestrictions.toArray( Appointment.EMPTY_ARRAY);
// Refresh the state of the "every Appointment" menu item
allMenu.setSelected(restriction.length == 0);
selectedMenu.setSelected(restriction.length != 0);
}
else if (source instanceof javax.swing.JCheckBoxMenuItem)
{
// Refresh the state of the "every Appointment" menu item
updateRestriction(Integer.valueOf(evt.getActionCommand()).intValue());
allMenu.setSelected(restriction.length == 0);
selectedMenu.setSelected(restriction.length != 0);
}
else
{
updateRestriction(Integer.valueOf(evt.getActionCommand()).intValue());
// "every Appointment" has been selected, stop editing
fireEditingStopped();
selectedTable.requestFocus();
}
if (oldRestrictionLength != restriction.length) {
RestrictionChange commando = new RestrictionChange( oldRestriction, restriction, selectedNode, selectedColumn);
commandHistory.storeAndExecute(commando);
}
}
public void popupMenuWillBecomeVisible(PopupMenuEvent e)
{
bStopEditingCalled = false;
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e)
{
if (!bStopEditingCalled)
{
AppointmentCellEditor.super.stopCellEditing();
}
}
public void popupMenuCanceled(PopupMenuEvent e)
{
// BUGID: 4234793
// This method is never called
}
Map<Integer,JMenuItem> appointmentList = new HashMap<Integer, JMenuItem>();
JMenuItem allMenu = new JRadioButtonMenuItem();
JMenuItem selectedMenu = new JRadioButtonMenuItem();
/**
* This method builds and shows the JPopupMenu for the appointment selection
*
* Changed in Rapla 1.4
*/
private void showComp()
{
Object selectedObject = selectedNode.getUserObject();
AllocationRendering allocBinding = null;
if (selectedObject instanceof Allocatable)
{
Allocatable allocatable = (Allocatable) selectedObject;
allocBinding = calcConflictingAppointments(allocatable);
}
Icon conflictIcon = getI18n().getIcon("icon.allocatable_taken");
allMenu.setText(getString("every_appointment"));
selectedMenu.setText(getString("selected_on"));
appointmentList.clear();
menu.removeAll();
allMenu.setActionCommand("-1");
allMenu.addActionListener(this);
selectedMenu.setActionCommand("-2");
selectedMenu.addActionListener( this );
selectedMenu.setUI(new StayOpenRadioButtonMenuItemUI());
menu.add(new JMenuItem(getString("close")));
menu.add(new JSeparator());
menu.add(allMenu);
menu.add(selectedMenu);
menu.add(new JSeparator());
for (int i = 0; i < appointments.length; i++)
{
JMenuItem item = new JCheckBoxMenuItem();
// Prevent the JCheckboxMenuItem from closing the JPopupMenu
item.setUI(new StayOpenCheckBoxMenuItemUI());
// set conflicting icon if appointment causes conflicts
String appointmentSummary = getAppointmentFormater().getShortSummary(appointments[i]);
if (allocBinding != null && allocBinding.conflictingAppointments[i])
{
item.setText((i + 1) + ": " + appointmentSummary);
item.setIcon(conflictIcon);
}
else
{
item.setText((i + 1) + ": " + appointmentSummary);
}
appointmentList.put(i, item);
item.setBackground(AWTColorUtil.getAppointmentColor(i));
item.setActionCommand(String.valueOf(i));
item.addActionListener(this);
menu.add(item);
}
for (int i = 0; i < appointments.length; i++)
{
appointmentList.get(i).setSelected(false);
}
Appointment[] apps = restriction;
allMenu.setSelected(apps.length == 0);
selectedMenu.setSelected(apps.length > 0);
for (int i = 0; i < apps.length; i++)
{
// System.out.println("Select " + indexOf(apps[i]));
appointmentList.get(indexOf(apps[i])).setSelected(true);
}
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension menuSize = menu.getPreferredSize();
Point location = editingComponent.getLocationOnScreen();
int diffx = Math.min(0, screenSize.width - (location.x + menuSize.width));
int diffy = Math.min(0, screenSize.height - (location.y + menuSize.height));
menu.show(editingComponent, diffx, diffy);
}
private void setRestriction(Appointment[] restriction)
{
this.restriction = restriction;
}
/** select or deselect the appointment at the given index */
private void updateRestriction(int index)
{
if (index == -1)
{
restriction = Appointment.EMPTY_ARRAY;
}
else if (index == -2)
{
restriction = appointments;
}
else
{
Collection<Appointment> newAppointments = new ArrayList<Appointment>();
// get the selected appointments
// add all previous selected appointments, except the appointment that
// is clicked
for (int i = 0; i < restriction.length; i++)
if (!restriction[i].equals(appointments[index]))
{
newAppointments.add(restriction[i]);
}
// If the clicked appointment was selected then deselect
// otherwise select ist
if (!containsAppointment(appointments[index]))
newAppointments.add(appointments[index]);
restriction = newAppointments.toArray(Appointment.EMPTY_ARRAY);
}
}
private boolean containsAppointment(Appointment appointment)
{
for (int i = 0; i < restriction.length; i++)
if (restriction[i].equals(appointment))
return true;
return false;
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
{
Component component = super.getTableCellEditorComponent(table, value, isSelected, row, column);
if (value instanceof Appointment[])
{
setRestriction((Appointment[]) value);
((RestrictionTextField) component).setText("");
}
((RestrictionTextField) component).setValue(value);
// Workaround for JDK 1.4 Bug ID: 4234793
// We have to change the table-model after cell-editing stopped
this.selectedNode = (DefaultMutableTreeNode) selectedTable.getTree().getPathForRow(row).getLastPathComponent();
this.selectedColumn = column;
return component;
}
public Object getCellEditorValue()
{
return restriction;
}
public boolean shouldSelectCell(EventObject event)
{
return true;
}
public boolean isCellEditable(EventObject event)
{
return true;
}
public boolean stopCellEditing()
{
bStopEditingCalled = true;
boolean bResult = super.stopCellEditing();
menu.setVisible(false);
return bResult;
}
}
class AppointmentCellEditor2 extends DefaultCellEditor implements MouseListener, KeyListener, PopupMenuListener, ActionListener
{
private static final long serialVersionUID = 1L;
JPopupMenu menu = new JPopupMenu();
AllocationTextField editingComponent;
boolean bStopEditingCalled = false; /*
* We need this variable
* to check if
* stopCellEditing
* was already called.
*/
DefaultMutableTreeNode selectedNode;
int selectedColumn = 0;
Appointment[] restriction;
public AppointmentCellEditor2(AllocationTextField textField)
{
super(textField);
editingComponent = (AllocationTextField) this.getComponent();
editingComponent.setEditable(false);
editingComponent.addMouseListener(this);
editingComponent.addKeyListener(this);
menu.addPopupMenuListener(this);
}
public void mouseReleased(MouseEvent evt)
{
showComp();
}
public void mousePressed(MouseEvent evt)
{
}
public void mouseClicked(MouseEvent evt)
{
}
public void mouseEntered(MouseEvent evt)
{
}
public void mouseExited(MouseEvent evt)
{
}
public void keyPressed(KeyEvent evt)
{
}
public void keyTyped(KeyEvent evt)
{
}
public void keyReleased(KeyEvent evt)
{
showComp();
}
/**
* This method is performed, if the user clicks on a menu item of the
* <code>JPopupMenu</code> in order to select invividual appointments
* for a resource.
*
*/
public void actionPerformed(ActionEvent evt)
{
}
public void popupMenuWillBecomeVisible(PopupMenuEvent e)
{
bStopEditingCalled = false;
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e)
{
if (!bStopEditingCalled)
{
AppointmentCellEditor2.super.stopCellEditing();
}
}
public void popupMenuCanceled(PopupMenuEvent e)
{
// BUGID: 4234793
// This method is never called
}
/**
* This method builds and shows the JPopupMenu for the appointment selection
*
*/
private void showComp()
{
Object selectedObject = selectedNode.getUserObject();
AllocationRendering allocBinding;
if (selectedObject != null && selectedObject instanceof Allocatable)
{
Allocatable allocatable = (Allocatable) selectedObject;
allocBinding = calcConflictingAppointments(allocatable);
}
else
{
return;
}
menu.removeAll();
boolean test = true;
for (int i = 0; i < appointments.length; i++)
{
if (allocBinding.conflictingAppointments[i])
test = false;
}
if ( test)
{
return;
}
else
{
for (int i = 0; i < appointments.length; i++)
{
if (allocBinding.conflictingAppointments[i])
continue;
JMenuItem item = new JMenuItem();
// Prevent the JCheckboxMenuItem from closing the JPopupMenu
// set conflicting icon if appointment causes conflicts
String appointmentSummary = getAppointmentFormater().getShortSummary(appointments[i]);
if (allocBinding.conflictingAppointments[i])
{
item.setText((i + 1) + ": " + appointmentSummary);
Icon conflictIcon = getI18n().getIcon("icon.allocatable_taken");
item.setIcon(conflictIcon);
}
else
{
item.setText((i + 1) + ": " + appointmentSummary);
}
item.setBackground(AWTColorUtil.getAppointmentColor(i));
menu.add(item);
}
}
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension menuSize = menu.getPreferredSize();
Point location = editingComponent.getLocationOnScreen();
int diffx = Math.min(0, screenSize.width - (location.x + menuSize.width));
int diffy = Math.min(0, screenSize.height - (location.y + menuSize.height));
menu.show(editingComponent, diffx, diffy);
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
{
Component component = super.getTableCellEditorComponent(table, value, isSelected, row, column);
if (value instanceof Allocatable)
{
((AllocationTextField) component).setText("");
}
((AllocationTextField) component).setValue(value);
// Workaround for JDK 1.4 Bug ID: 4234793
// We have to change the table-model after cell-editing stopped
this.selectedNode = (DefaultMutableTreeNode) completeTable.getTree().getPathForRow(row).getLastPathComponent();
this.selectedColumn = column;
return component;
}
public Object getCellEditorValue()
{
return restriction;
}
public boolean shouldSelectCell(EventObject event)
{
return true;
}
public boolean isCellEditable(EventObject event)
{
return true;
}
public boolean stopCellEditing()
{
bStopEditingCalled = true;
boolean bResult = super.stopCellEditing();
menu.setVisible(false);
return bResult;
}
}
class AllocationTreeCellRenderer extends DefaultTreeCellRenderer
{
private static final long serialVersionUID = 1L;
Icon conflictIcon;
Icon freeIcon;
Icon notAlwaysAvailableIcon;
Icon personIcon;
Icon personNotAlwaysAvailableIcon;
Icon forbiddenIcon;
boolean checkRestrictions;
public AllocationTreeCellRenderer(boolean checkRestrictions)
{
forbiddenIcon = getI18n().getIcon("icon.no_perm");
conflictIcon = getI18n().getIcon("icon.allocatable_taken");
freeIcon = getI18n().getIcon("icon.allocatable_available");
notAlwaysAvailableIcon = getI18n().getIcon("icon.allocatable_not_always_available");
personIcon = getI18n().getIcon("icon.tree.persons");
personNotAlwaysAvailableIcon = getI18n().getIcon("icon.tree.person_not_always_available");
this.checkRestrictions = checkRestrictions;
setOpenIcon(getI18n().getIcon("icon.folder"));
setClosedIcon(getI18n().getIcon("icon.folder"));
setLeafIcon(freeIcon);
}
public Icon getAvailableIcon(Allocatable allocatable)
{
if (allocatable.isPerson())
return personIcon;
else
return freeIcon;
}
public Icon getNotAlwaysAvailableIcon(Allocatable allocatable)
{
if (allocatable.isPerson())
return personNotAlwaysAvailableIcon;
else
return notAlwaysAvailableIcon;
}
private Icon getIcon(Allocatable allocatable)
{
AllocationRendering allocBinding = calcConflictingAppointments(allocatable);
if (allocBinding.conflictCount == 0)
{
return getAvailableIcon(allocatable);
}
else if (allocBinding.conflictCount == appointments.length)
{
if (allocBinding.conflictCount == allocBinding.permissionConflictCount)
{
if (!checkRestrictions)
{
return forbiddenIcon;
}
}
else
{
return conflictIcon;
}
}
else if (!checkRestrictions)
{
return getNotAlwaysAvailableIcon(allocatable);
}
for (int i = 0; i < appointments.length; i++)
{
Appointment appointment = appointments[i];
if (mutableReservation.hasAllocated(allocatable, appointment) && !hasPermissionToAllocate(appointment, allocatable))
{
return forbiddenIcon;
}
}
if (allocBinding.permissionConflictCount - allocBinding.conflictCount == 0)
{
return getAvailableIcon(allocatable);
}
Appointment[] restriction = mutableReservation.getRestriction(allocatable);
if (restriction.length == 0)
{
return conflictIcon;
}
else
{
boolean conflict = false;
for (int i = 0; i < restriction.length; i++)
{
Collection<Appointment> list = allocatableBindings.get( allocatable);
if (list.contains( restriction[i]) )
{
conflict = true;
break;
}
}
if (conflict)
return conflictIcon;
else
return getNotAlwaysAvailableIcon(allocatable);
}
}
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus)
{
DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
Object nodeInfo = node.getUserObject();
Locale locale = getI18n().getLocale();
if (nodeInfo != null && nodeInfo instanceof Named)
{
value = ((Named) nodeInfo).getName(locale);
}
if (leaf)
{
if (nodeInfo instanceof Allocatable)
{
Allocatable allocatable = (Allocatable) nodeInfo;
setLeafIcon(getIcon(allocatable));
Classification classification = allocatable.getClassification();
if ( classification.getType().getAnnotation(DynamicTypeAnnotations.KEY_NAME_FORMAT_PLANNING) != null)
{
value = classification.getNamePlaning(locale);
}
}
}
Component result = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
return result;
}
}
public boolean hasPermissionToAllocate(Appointment appointment,
Allocatable allocatable) {
Date today = getQuery().today();
User workingUser;
try {
workingUser = getUser();
} catch (RaplaException ex) {
getLogger().error("Can't get permissions!", ex);
return false;
}
if (originalReservation == null)
{
return allocatable.canAllocate(workingUser, appointment.getStart(), appointment.getMaxEnd(),today);
}
else
{
return FacadeImpl.hasPermissionToAllocate(workingUser, appointment, allocatable, originalReservation, today);
}
}
class AllocatableAction extends AbstractAction
{
private static final long serialVersionUID = 1L;
String command;
AllocatableAction(String command)
{
this.command = command;
if (command.equals("add"))
{
putValue(NAME, getString("add"));
putValue(SMALL_ICON, getIcon("icon.arrow_right"));
}
if (command.equals("remove"))
{
putValue(NAME, getString("remove"));
putValue(SMALL_ICON, getIcon("icon.arrow_left"));
}
if (command.equals("calendar1") || command.equals("calendar2"))
{
putValue(NAME, getString("calendar"));
putValue(SMALL_ICON, getIcon("icon.calendar"));
}
}
public void actionPerformed(ActionEvent evt)
{
if (command.equals("add")) {
AllocatableChange commando = newAllocatableChange(command,completeTable);
commandHistory.storeAndExecute(commando);
}
if (command.equals("remove")) {
AllocatableChange commando = newAllocatableChange(command,selectedTable);
commandHistory.storeAndExecute(commando);
}
if (command.indexOf("calendar") >= 0)
{
JTreeTable tree = (command.equals("calendar1") ? completeTable : selectedTable);
CalendarAction calendarAction = new CalendarAction(getContext(), getComponent(), calendarModel);
calendarAction.changeObjects(new ArrayList<Object>(getSelectedAllocatables(tree.getTree())));
Collection<Appointment> appointments = Arrays.asList( AllocatableSelection.this.appointments);
calendarAction.setStart(findFirstStart(appointments));
calendarAction.actionPerformed(evt);
}
}
}
/**
* This class is used to prevent the JPopupMenu from disappearing when a
* <code>JCheckboxMenuItem</code> is clicked.
*
* @since Rapla 1.4
* @see http://forums.oracle.com/forums/thread.jspa?messageID=5724401#5724401
*/
class StayOpenCheckBoxMenuItemUI extends BasicCheckBoxMenuItemUI
{
protected void doClick(MenuSelectionManager msm)
{
menuItem.doClick(0);
}
}
class StayOpenRadioButtonMenuItemUI extends BasicRadioButtonMenuItemUI
{
protected void doClick(MenuSelectionManager msm)
{
menuItem.doClick(0);
}
}
private AllocatableChange newAllocatableChange(String command,JTreeTable treeTable)
{
Collection<Allocatable> elements = getSelectedAllocatables( treeTable.getTree());
return new AllocatableChange(command, elements);
}
public static Color darken(Color color, int i) {
int newBlue = Math.max( color.getBlue() - i, 0);
int newRed = Math.max( color.getRed() - i, 0);
int newGreen = Math.max( color.getGreen() - i, 0);
return new Color( newRed, newGreen,newBlue, color.getAlpha());
}
/**
* This Class collects any information changes done to selected or deselected allocatables.
* This is where undo/redo for the Allocatable-selection at the bottom of the edit view
* is realized.
* @author Jens Fritz
*
*/
//Erstellt und bearbeitet von Matthias Both und Jens Fritz
public class AllocatableChange implements CommandUndo<RuntimeException> {
String command;
Collection<Allocatable> elements;
public AllocatableChange(String command,
Collection<Allocatable> elements) {
this.command = command;
List<Allocatable> changed = new ArrayList<Allocatable>();
boolean addOrRemove;
if (command.equals("add"))
addOrRemove = false;
else
addOrRemove = true;
Iterator<Allocatable> it = elements.iterator();
while (it.hasNext()) {
Allocatable a = it.next();
if (mutableReservation.hasAllocated(a) == addOrRemove) {
changed.add(a);
}
}
this.elements = changed;
}
public boolean execute() {
if (command.equals("add"))
add(elements);
else
remove(elements);
return true;
}
public boolean undo() {
if (command.equals("add"))
remove(elements);
else
add(elements);
return true;
}
public String getCommandoName()
{
return getString(command) + " " + getString("resource");
}
}
/**
* This Class collects any information of changes done to the exceptions
* of an selected allocatable.
* This is where undo/redo for the Allocatable-exceptions at the bottom of the edit view
* is realized.
* @author Jens Fritz
*
*/
//Erstellt von Matthias Both
public class RestrictionChange implements CommandUndo<RuntimeException> {
Appointment[] oldRestriction;
Appointment[] newRestriction;
DefaultMutableTreeNode selectedNode;
int selectedColumn;
public RestrictionChange(Appointment[] old, Appointment[] newOne,
DefaultMutableTreeNode selectedNode, int selectedColummn) {
this.oldRestriction = old;
this.newRestriction = newOne;
this.selectedNode = selectedNode;
this.selectedColumn = selectedColummn;
}
public boolean execute() {
selectedModel.setValueAt(newRestriction, selectedNode,
selectedColumn);
return true;
}
public boolean undo() {
selectedModel.setValueAt(oldRestriction, selectedNode,
selectedColumn);
return true;
}
public String getCommandoName()
{
return getString("change") + " " + getString("constraints");
}
}
} | 04900db4-rob | src/org/rapla/gui/internal/edit/reservation/AllocatableSelection.java | Java | gpl3 | 64,972 |