From 7f5bbbdc56fa18cfc94ea649e9f1337301906e19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Axel=20D=C3=B6rfler?= Date: Fri, 26 Jun 2009 11:58:43 +0000 Subject: [PATCH] * Removed PI, and PI2 from math.h. * Replaced all occurences with the standard macros M_PI, and M_PI_2. * Some coding style cleanup on the touched files, no other changes besides adding a missing check for a failed memory allocation. git-svn-id: file:///srv/svn/repos/haiku/haiku/trunk@31250 a95241bf-73f2-0310-859d-f6bbb57e9c96 --- headers/posix/math.h | 301 +++-- .../accelerants/intel_extreme/overlay.cpp | 11 +- .../print/drivers/pdf/source/PDFText.cpp | 335 +++-- .../print/drivers/pdf/source/PDFWriter.cpp | 1184 ++++++++--------- .../print/drivers/pdf/source/PDFWriter.h | 117 +- .../cortex/addons/Flanger/FlangerNode.cpp | 418 +++--- src/apps/fontdemo/FontDemoView.cpp | 44 +- .../icon-o-matic/generic/support/support.cpp | 28 +- .../transformable/CanvasTransformBox.cpp | 17 +- .../transformable/ChannelTransform.cpp | 65 +- .../transformable/TransformBox.cpp | 148 ++- .../transformable/TransformBoxStates.cpp | 190 +-- .../transformable/TransformGradientBox.cpp | 42 +- src/libs/icon/shape/VectorPath.cpp | 507 ++++--- src/libs/icon/transformable/Transformable.cpp | 16 +- .../screensaver/ScreenCornerSelector.cpp | 55 +- src/preferences/time/AnalogClock.cpp | 184 +-- src/servers/app/ServerFont.cpp | 6 +- .../app/drawing/Painter/AGGTextRenderer.cpp | 4 +- src/servers/app/drawing/Painter/Painter.cpp | 17 +- 20 files changed, 1840 insertions(+), 1849 deletions(-) diff --git a/headers/posix/math.h b/headers/posix/math.h index abad6a5b29..85dbb65aaa 100644 --- a/headers/posix/math.h +++ b/headers/posix/math.h @@ -1,5 +1,5 @@ /* - * Copyright 2001-2006, Haiku. + * Copyright 2001-2009, Haiku. * Distributed under the terms of the MIT License. */ #ifndef _MATH_H_ @@ -20,9 +20,6 @@ #define M_SQRT2 1.41421356237309504880 /* sqrt(2) */ #define M_SQRT1_2 0.70710678118654752440 /* 1/sqrt(2) */ -#define PI M_PI -#define PI2 M_PI_2 - /* platform independent IEEE floating point special values */ #define __HUGE_VAL_v 0x7ff0000000000000LL #define __huge_val_t union { unsigned char __c[8]; long long __ll; double __d; } @@ -34,7 +31,7 @@ #define __huge_valf_t union { unsigned char __c[4]; long __l; float __f; } #define HUGE_VALF (((__huge_valf_t) { __l: __HUGE_VALF_v }).__f) -/* ToDo: define HUGE_VALL for long doubles */ +/* TODO: define HUGE_VALL for long doubles */ #define __NAN_VALF_v 0x7fc00000L #define NAN (((__huge_valf_t) { __l: __NAN_VALF_v }).__f) @@ -79,149 +76,149 @@ extern "C" { #endif /* float math functions */ -extern float acosf(float x); -extern float acoshf(float x); -extern float asinf(float x); -extern float asinhf(float x); -extern float atan2f(float y, float x); -extern float atanf(float x); -extern float atanhf(float x); -extern float cbrtf(float x); -extern float ceilf(float x); -extern float cosf(float x); -extern float coshf(float x); -extern float expf(float x); -extern float expm1f(float x); -extern float fabsf(float x); -extern float floorf(float x); -extern float fmodf(float x, float y); -extern float frexpf(float x, int *_exponent); -extern float gammaf(float x); -extern float hypotf(float x, float y); -extern float ldexpf(float x, int exponent); -extern float lgammaf(float x); -extern long long llrintf(float x); -extern float log10f(float x); -extern float log1pf(float x); -extern float logbf(float x); -extern float logf(float x); -extern long lrintf(float x); -extern long lroundf(float x); -extern float modff(float x, float *y); -extern float nearbyintf(float x); -extern float powf(float x, float y); -extern float remquof(float x, float y, int *quo); -extern float roundf(float x); -extern float sinf(float x); -extern float sinhf(float x); -extern float sqrtf(float x); -extern float tanf(float x); -extern float tanhf(float x); +extern float acosf(float x); +extern float acoshf(float x); +extern float asinf(float x); +extern float asinhf(float x); +extern float atan2f(float y, float x); +extern float atanf(float x); +extern float atanhf(float x); +extern float cbrtf(float x); +extern float ceilf(float x); +extern float cosf(float x); +extern float coshf(float x); +extern float expf(float x); +extern float expm1f(float x); +extern float fabsf(float x); +extern float floorf(float x); +extern float fmodf(float x, float y); +extern float frexpf(float x, int *_exponent); +extern float gammaf(float x); +extern float hypotf(float x, float y); +extern float ldexpf(float x, int exponent); +extern float lgammaf(float x); +extern long long llrintf(float x); +extern float log10f(float x); +extern float log1pf(float x); +extern float logbf(float x); +extern float logf(float x); +extern long lrintf(float x); +extern long lroundf(float x); +extern float modff(float x, float *y); +extern float nearbyintf(float x); +extern float powf(float x, float y); +extern float remquof(float x, float y, int *quo); +extern float roundf(float x); +extern float sinf(float x); +extern float sinhf(float x); +extern float sqrtf(float x); +extern float tanf(float x); +extern float tanhf(float x); /* double math functions */ -extern double acos(double x); -extern double acosh(double x); -extern double asin(double x); -extern double asinh(double x); -extern double atan(double x); -extern double atan2(double x, double y); -extern double atanh(double x); -extern double ceil(double x); -extern double cos(double x); -extern double cosh(double x); -extern double exp(double x); -extern double fabs(double x); -extern double floor(double x); -extern double fmod(double x, double y); -extern double frexp(double x, int *_exponent); -extern double gamma(double x); -extern double ldexp(double x, int exponent); -extern double lgamma(double x); -extern long long llrint(double x); -extern double log(double x); -extern double log10(double x); -extern long lrint(double x); -extern long lround(double x); -extern double modf(double x, double *y); -extern double nearbyint(double x); -extern double pow(double x, double y); -extern double remquo(double x, double y, int *quo); -extern double round(double x); -extern double sin(double x); -extern double sinh(double x); -extern double sqrt(double x); -extern double tan(double x); -extern double tanh(double x); -extern double trunc(double x); +extern double acos(double x); +extern double acosh(double x); +extern double asin(double x); +extern double asinh(double x); +extern double atan(double x); +extern double atan2(double x, double y); +extern double atanh(double x); +extern double ceil(double x); +extern double cos(double x); +extern double cosh(double x); +extern double exp(double x); +extern double fabs(double x); +extern double floor(double x); +extern double fmod(double x, double y); +extern double frexp(double x, int *_exponent); +extern double gamma(double x); +extern double ldexp(double x, int exponent); +extern double lgamma(double x); +extern long long llrint(double x); +extern double log(double x); +extern double log10(double x); +extern long lrint(double x); +extern long lround(double x); +extern double modf(double x, double *y); +extern double nearbyint(double x); +extern double pow(double x, double y); +extern double remquo(double x, double y, int *quo); +extern double round(double x); +extern double sin(double x); +extern double sinh(double x); +extern double sqrt(double x); +extern double tan(double x); +extern double tanh(double x); +extern double trunc(double x); /* long double math functions */ -extern long double acosl(long double x); -extern long double acoshl(long double x); -extern long double asinl(long double x); -extern long double atanl(long double x); -extern long double atanhl(long double x); -extern long double atan2l(long double y, long double x); +extern long double acosl(long double x); +extern long double acoshl(long double x); +extern long double asinl(long double x); +extern long double atanl(long double x); +extern long double atanhl(long double x); +extern long double atan2l(long double y, long double x); extern long double lgammal(long double x); -extern long double nearbyintl(long double x); +extern long double nearbyintl(long double x); extern long long llrintl(long double x); -extern long lrintl(long double x); -extern long lroundl(long double x); -extern long double remquol(long double x, long double y, int *quo); +extern long lrintl(long double x); +extern long lroundl(long double x); +extern long double remquol(long double x, long double y, int *quo); extern long double roundl(long double x); /* some BSD non-ANSI or POSIX math functions */ -extern double cbrt(double x); -extern double erf(double x); -extern double erfc(double x); -extern double expm1(double x); -extern double gamma_r(double x, int *y); -extern double hypot(double x, double y); -extern int ilogb(double x); -extern double j0(double x); -extern double j1(double x); -extern double jn(int x, double y); -extern double lgamma_r(double x, int *y); -extern double log1p(double x); -extern double logb(double x); -extern double nextafter(double x, double y); -extern double nexttoward(double x, long double y); -extern double remainder(double x, double y); -extern double rint(double x); -extern double scalb (double x, double y); -extern double y0(double x); -extern double y1(double x); -extern double yn(int x, double y); +extern double cbrt(double x); +extern double erf(double x); +extern double erfc(double x); +extern double expm1(double x); +extern double gamma_r(double x, int *y); +extern double hypot(double x, double y); +extern int ilogb(double x); +extern double j0(double x); +extern double j1(double x); +extern double jn(int x, double y); +extern double lgamma_r(double x, int *y); +extern double log1p(double x); +extern double logb(double x); +extern double nextafter(double x, double y); +extern double nexttoward(double x, long double y); +extern double remainder(double x, double y); +extern double rint(double x); +extern double scalb (double x, double y); +extern double y0(double x); +extern double y1(double x); +extern double yn(int x, double y); /* other stuff as defined in BeOS */ -extern int isinff(float value); -extern int finitef(float value); -extern float dremf(float x, float y); -extern float significandf(float x); -extern float copysignf(float x, float y); -extern int isnanf(float value); -extern double significand(double x); -extern double copysign(double x, double y); -extern double scalbln(double x, long n); -extern double scalbn(double x, int y); -extern double drem(double x, double y); -extern int finite(double x); -extern float j0f(float x); -extern float j1f(float x); -extern float jnf(int x, float y); -extern float y0f(float x); -extern float y1f(float x); -extern float ynf(int x, float y); -extern float erff(float x); -extern float erfcf(float x); -extern float gammaf_r(float x, int *y); -extern float lgammaf_r(float x, int *y); -extern float rintf(float x); -extern float nextafterf(float x, float y); -extern float nexttowardf(float x, long double y); -extern float remainderf(float x, float y); -extern float scalbf(float x, float n); -extern float scalbnf(float x, int n); -extern int ilogbf(float x); +extern int isinff(float value); +extern int finitef(float value); +extern float dremf(float x, float y); +extern float significandf(float x); +extern float copysignf(float x, float y); +extern int isnanf(float value); +extern double significand(double x); +extern double copysign(double x, double y); +extern double scalbln(double x, long n); +extern double scalbn(double x, int y); +extern double drem(double x, double y); +extern int finite(double x); +extern float j0f(float x); +extern float j1f(float x); +extern float jnf(int x, float y); +extern float y0f(float x); +extern float y1f(float x); +extern float ynf(int x, float y); +extern float erff(float x); +extern float erfcf(float x); +extern float gammaf_r(float x, int *y); +extern float lgammaf_r(float x, int *y); +extern float rintf(float x); +extern float nextafterf(float x, float y); +extern float nexttowardf(float x, long double y); +extern float remainderf(float x, float y); +extern float scalbf(float x, float n); +extern float scalbnf(float x, int n); +extern int ilogbf(float x); extern long double nextafterl(long double x, long double y); extern long double nexttowardl(long double x, long double y); @@ -231,23 +228,23 @@ extern long double scalbnl(long double x, int n); extern long double scalblnl(long double x, long n); /* prototypes for functions used in the macros below */ -extern int __fpclassifyf(float value); -extern int __signbitf(float value); -extern int __finitef(float value); -extern int __isnanf(float value); -extern int __isinff(float value); +extern int __fpclassifyf(float value); +extern int __signbitf(float value); +extern int __finitef(float value); +extern int __isnanf(float value); +extern int __isinff(float value); -extern int __fpclassifyl(long double value); -extern int __signbitl(long double value); -extern int __finitel(long double value); -extern int __isnanl(long double value); -extern int __isinfl(long double value); +extern int __fpclassifyl(long double value); +extern int __signbitl(long double value); +extern int __finitel(long double value); +extern int __isnanl(long double value); +extern int __isinfl(long double value); -extern int __fpclassify(double value); -extern int __signbit(double value); -extern int __finite(double value); -extern int __isnan(double value); -extern int __isinf(double value); +extern int __fpclassify(double value); +extern int __signbit(double value); +extern int __finite(double value); +extern int __isnan(double value); +extern int __isinf(double value); /* returns number of classification appropriate for 'value' */ #define fpclassify(value) \ diff --git a/src/add-ons/accelerants/intel_extreme/overlay.cpp b/src/add-ons/accelerants/intel_extreme/overlay.cpp index 23841b2613..db6318717a 100644 --- a/src/add-ons/accelerants/intel_extreme/overlay.cpp +++ b/src/add-ons/accelerants/intel_extreme/overlay.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2006-2008, Haiku, Inc. All Rights Reserved. + * Copyright 2006-2009, Haiku, Inc. All Rights Reserved. * Distributed under the terms of the MIT License. * * Authors: @@ -109,14 +109,15 @@ update_coefficients(int32 taps, double filterCutOff, bool horizontal, bool isY, int32 num = taps * 16; for (int32 i = 0; i < num * 2; i++) { double sinc; - double value = (1.0 / filterCutOff) * taps * PI * (i - num) / (2 * num); + double value = (1.0 / filterCutOff) * taps * M_PI * (i - num) + / (2 * num); if (value == 0.0) sinc = 1.0; else sinc = sin(value) / value; // Hamming window - double window = (0.5 - 0.5 * cos(i * PI / num)); + double window = (0.5 - 0.5 * cos(i * M_PI / num)); rawCoefficients[i] = sinc * window; } @@ -346,10 +347,10 @@ intel_allocate_overlay_buffer(color_space colorSpace, uint16 width, bytesPerPixel = 2; break; case B_RGB16: - bytesPerPixel = 2; + bytesPerPixel = 2; break; case B_RGB32: - bytesPerPixel = 4; + bytesPerPixel = 4; break; case B_YCbCr422: bytesPerPixel = 2; diff --git a/src/add-ons/print/drivers/pdf/source/PDFText.cpp b/src/add-ons/print/drivers/pdf/source/PDFText.cpp index 0299d77f3a..e3c82f0c80 100644 --- a/src/add-ons/print/drivers/pdf/source/PDFText.cpp +++ b/src/add-ons/print/drivers/pdf/source/PDFText.cpp @@ -1,36 +1,15 @@ /* - -PDF Writer printer driver. - -Copyright (c) 2001, 2002 OpenBeOS. - -Authors: - Philippe Houdoin - Simon Gauvin - Michael Pfeiffer - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -*/ + * Copyright 2001-2009, Haiku, Inc. All Rights Reserved. + * Distributed under the terms of the MIT License. + * + * Authors: + * Philippe Houdoin + * Simon Gauvin + * Michael Pfeiffer + */ #include -#include +#include #include #include @@ -47,28 +26,26 @@ THE SOFTWARE. #include "Report.h" #include "pdflib.h" -typedef struct -{ + +typedef struct { uint16 from; uint16 to; int16 length; uint16 *unicodes; } unicode_to_encoding; -typedef struct -{ +typedef struct { uint16 unicode; uint16 cid; } unicode_to_cid; -typedef struct -{ +typedef struct { uint16 length; - unicode_to_cid *table; + unicode_to_cid *table; } cid_table; #ifdef UNICODE5_FROM - #error check code! +# error check code! #endif #define ELEMS(v, e) sizeof(v) / sizeof(e) @@ -81,8 +58,8 @@ typedef struct #include "unicode3.h" #include "unicode4.h" -static unicode_to_encoding encodings[] = -{ + +static unicode_to_encoding encodings[] = { {UNICODE0_FROM, UNICODE0_TO, ELEMS(unicode0, uint16), unicode0}, {UNICODE1_FROM, UNICODE1_TO, ELEMS(unicode1, uint16), unicode1}, {UNICODE2_FROM, UNICODE2_TO, ELEMS(unicode2, uint16), unicode2}, @@ -97,18 +74,40 @@ static unicode_to_encoding encodings[] = #include "korean.h" -static cid_table cid_tables[] = -{ +static cid_table cid_tables[] = { {ELEMS(japanese, unicode_to_cid), japanese}, {ELEMS(CNS1, unicode_to_cid), CNS1}, {ELEMS(GB1, unicode_to_cid), GB1}, {ELEMS(korean, unicode_to_cid), korean} }; +static const char* encoding_names[] = { + "macroman", + // TrueType + "ttenc0", + "ttenc1", + "ttenc2", + "ttenc3", + "ttenc4", + // Type 1 + "t1enc0", + "t1enc1", + "t1enc2", + "t1enc3", + "t1enc4", + // CJK + "UniJIS-UCS2-H", + "UniCNS-UCS2-H", + "UniGB-UCS2-H", + "UniKS-UCS2-H" +}; -// -------------------------------------------------- -static bool -find_encoding(uint16 unicode, uint8 &encoding, uint16 &index) + +// #pragma mark - + + +static bool +find_encoding(uint16 unicode, uint8 &encoding, uint16 &index) { for (unsigned int i = 0; i < ELEMS(encodings, unicode_to_encoding); i++) { if (encodings[i].from <= unicode && unicode <= encodings[i].to) { @@ -128,15 +127,15 @@ find_encoding(uint16 unicode, uint8 &encoding, uint16 &index) } } return false; - } + } } return false; } -// -------------------------------------------------- -static bool -find_in_cid_tables(uint16 unicode, font_encoding &encoding, uint16 &index, font_encoding* order) +static bool +find_in_cid_tables(uint16 unicode, font_encoding &encoding, uint16 &index, + font_encoding* order) { for (unsigned int i = 0; i < ELEMS(cid_tables, cid_table); i++) { encoding = order[i]; @@ -161,9 +160,9 @@ find_in_cid_tables(uint16 unicode, font_encoding &encoding, uint16 &index, font_ } -// -------------------------------------------------- void -PDFWriter::MakeUserDefinedEncoding(uint16 unicode, uint8 &enc, uint8 &index) { +PDFWriter::MakeUserDefinedEncoding(uint16 unicode, uint8 &enc, uint8 &index) +{ if (fUserDefinedEncodings.Get(unicode, enc, index)) { BString s("user"); s << (int)enc; @@ -171,24 +170,25 @@ PDFWriter::MakeUserDefinedEncoding(uint16 unicode, uint8 &enc, uint8 &index) { } } -// -------------------------------------------------- + void -PDFWriter::RecordFont(const char* family, const char* style, float size) { +PDFWriter::RecordFont(const char* family, const char* style, float size) +{ const int32 n = fUsedFonts.CountItems(); for (int32 i = 0; i < n; i ++) { if (fUsedFonts.ItemAt(i)->Equals(family, style, size)) return; } - + UsedFont* font; font = new UsedFont(family, style, size); fUsedFonts.AddItem(font); - + REPORT(kInfo, -1, "Used font: \"%s\" \"%s\" %f", family, style, size); } -// -------------------------------------------------- -void -PDFWriter::GetFontName(BFont *font, char *fontname) + +void +PDFWriter::GetFontName(BFont *font, char *fontname) { font_family family; font_style style; @@ -199,9 +199,10 @@ PDFWriter::GetFontName(BFont *font, char *fontname) RecordFont(family, style, font->Size()); } -// -------------------------------------------------- -void -PDFWriter::GetFontName(BFont *font, char *fontname, bool &embed, font_encoding encoding) + +void +PDFWriter::GetFontName(BFont *font, char *fontname, bool &embed, + font_encoding encoding) { GetFontName(font, fontname); @@ -219,38 +220,15 @@ PDFWriter::GetFontName(BFont *font, char *fontname, bool &embed, font_encoding e } -static const char* encoding_names[] = -{ - "macroman", - // TrueType - "ttenc0", - "ttenc1", - "ttenc2", - "ttenc3", - "ttenc4", - // Type 1 - "t1enc0", - "t1enc1", - "t1enc2", - "t1enc3", - "t1enc4", - // CJK - "UniJIS-UCS2-H", - "UniCNS-UCS2-H", - "UniGB-UCS2-H", - "UniKS-UCS2-H" -}; - - -// -------------------------------------------------- -int -PDFWriter::FindFont(char* fontName, bool embed, font_encoding encoding) +int +PDFWriter::FindFont(char* fontName, bool embed, font_encoding encoding) { static Font* cache = NULL; - if (cache && cache->encoding == encoding && strcmp(cache->name.String(), fontName) == 0) + if (cache && cache->encoding == encoding + && strcmp(cache->name.String(), fontName) == 0) return cache->font; - REPORT(kDebug, fPage, "FindFont %s", fontName); + REPORT(kDebug, fPage, "FindFont %s", fontName); Font *f = NULL; const int n = fFontCache.CountItems(); for (int i = 0; i < n; i++) { @@ -260,33 +238,34 @@ PDFWriter::FindFont(char* fontName, bool embed, font_encoding encoding) return f->font; } } - + if (embed) embed = EmbedFont(fontName); BString s; const char* encoding_name; - if (encoding < user_defined_encoding_start) { + if (encoding < user_defined_encoding_start) { encoding_name = encoding_names[encoding]; } else { s = "user"; s << (int)(encoding - user_defined_encoding_start); encoding_name = s.String(); } - REPORT(kDebug, fPage, "Create new font, %sembed, encoding %s", embed ? "" : "do not ", encoding_name); + REPORT(kDebug, fPage, "Create new font, %sembed, encoding %s", + embed ? "" : "do not ", encoding_name); int font = PDF_findfont(fPdf, fontName, encoding_name, embed); if (font != -1) { REPORT(kDebug, fPage, "font created"); cache = new Font(fontName, font, encoding); fFontCache.AddItem(cache); } else { - REPORT(kError, fPage, "Could not create font '%s': %s", fontName, PDF_get_errmsg(fPdf)); + REPORT(kError, fPage, "Could not create font '%s': %s", fontName, + PDF_get_errmsg(fPdf)); } return font; } -// -------------------------------------------------- -void +void PDFWriter::ToUtf8(uint32 encoding, const char *string, BString &utf8) { int32 len = strlen(string); @@ -296,19 +275,19 @@ PDFWriter::ToUtf8(uint32 encoding, const char *string, BString &utf8) int32 srcStart = 0; do { - convert_to_utf8(encoding, &string[srcStart], &srcLen, buffer, &destLen, &state); + convert_to_utf8(encoding, &string[srcStart], &srcLen, buffer, &destLen, + &state); srcStart += srcLen; len -= srcLen; srcLen = len; - + utf8.Append(buffer, destLen); destLen = 255; } while (len > 0); }; -// -------------------------------------------------- -void +void PDFWriter::ToUnicode(const char *string, BString &unicode) { int32 len = strlen(string); @@ -318,87 +297,90 @@ PDFWriter::ToUnicode(const char *string, BString &unicode) int32 srcStart = 0; int i = 0; - unicode = ""; + unicode = ""; if (len == 0) return; do { - convert_from_utf8(B_UNICODE_CONVERSION, &string[srcStart], &srcLen, buffer, &destLen, &state); + convert_from_utf8(B_UNICODE_CONVERSION, &string[srcStart], &srcLen, + buffer, &destLen, &state); srcStart += srcLen; len -= srcLen; srcLen = len; char *b = unicode.LockBuffer(i + destLen); memcpy(&b[i], buffer, destLen); - unicode.UnlockBuffer(i + destLen); + unicode.UnlockBuffer(i + destLen); i += destLen; destLen = 255; } while (len > 0); } -// -------------------------------------------------- -void +void PDFWriter::ToPDFUnicode(const char *string, BString &unicode) { // PDFlib requires BOM at begin and two 0 at end of string char marker[3] = { 0xfe, 0xff, 0}; // byte order marker BString s; ToUnicode(string, s); - unicode << marker; - int32 len = s.Length()+2; - char* buf = unicode.LockBuffer(len + 2); // reserve space for two additional '\0' + unicode << marker; + int32 len = s.Length()+2; + char* buf = unicode.LockBuffer(len + 2); + // reserve space for two additional '\0' memcpy(&buf[2], s.String(), s.Length()); buf[len] = buf[len+1] = 0; unicode.UnlockBuffer(len + 2); } -// -------------------------------------------------- -uint16 +uint16 PDFWriter::CodePointSize(const char* s) { uint16 i = 1; - for (s++; !BeginsChar(*s); s++) i++; + for (s++; !BeginsChar(*s); s++) i++; return i; } -void PDFWriter::RecordDests(const char* s) { +void +PDFWriter::RecordDests(const char* s) +{ ::RecordDests record(fXRefDests, &fTextLine, fPage); fXRefs->Matches(s, &record, true); } - -// -------------------------------------------------- void PDFWriter::DrawChar(uint16 unicode, const char* utf8, int16 size) { // try to convert from utf8 to MacRoman encoding schema... int32 srcLen = size; int32 destLen = 1; - char dest[3] = "\0\0"; - int32 state = 0; + char dest[3] = "\0\0"; + int32 state = 0; bool embed = true; - font_encoding encoding = macroman_encoding; - char fontName[B_FONT_FAMILY_LENGTH+B_FONT_STYLE_LENGTH+1]; - - if (convert_from_utf8(B_MAC_ROMAN_CONVERSION, utf8, &srcLen, dest, &destLen, &state, 0) != B_OK || dest[0] == 0 ) { + font_encoding encoding = macroman_encoding; + char fontName[B_FONT_FAMILY_LENGTH+B_FONT_STYLE_LENGTH+1]; + + if (convert_from_utf8(B_MAC_ROMAN_CONVERSION, utf8, &srcLen, dest, &destLen, + &state, 0) != B_OK || dest[0] == 0) { // could not convert to MacRoman - uint8 enc; - uint16 index = 0; font_encoding fenc; + uint16 index = 0; + uint8 enc; GetFontName(&fState->beFont, fontName); embed = EmbedFont(fontName); - + REPORT(kDebug, -1, "find_encoding unicode %d\n", (int)unicode); if (find_encoding(unicode, enc, index)) { // is code point in the Adobe Glyph List? - // Note if rendering the glyphs only would be desired, we could always use - // the second method below (MakeUserDefinedEncoding), but extracting text - // from the generated PDF would be almost impossible (OCR!) - REPORT(kDebug, -1, "encoding for %x -> %d %d", unicode, (int)enc, (int)index); + // Note if rendering the glyphs only would be desired, we could + // always use the second method below (MakeUserDefinedEncoding), + // but extracting text from the generated PDF would be almost + // impossible (OCR!) + REPORT(kDebug, -1, "encoding for %x -> %d %d", unicode, (int)enc, + (int)index); // use one of the user pre-defined encodings if (fState->beFont.FileFormat() == B_TRUETYPE_WINDOWS) { encoding = font_encoding(enc + tt_encoding0); @@ -415,8 +397,8 @@ PDFWriter::DrawChar(uint16 unicode, const char* utf8, int16 size) } else if (find_in_cid_tables(unicode, fenc, index, fFontSearchOrder)) { // font is not embedded use one of the CJK fonts for substitution REPORT(kDebug, -1, "cid table %d index = %d", (int)fenc, (int)index); - dest[0] = unicode / 256; - dest[1] = unicode % 256; + dest[0] = unicode / 256; + dest[1] = unicode % 256; destLen = 2; encoding = fenc; embed = false; @@ -425,33 +407,40 @@ PDFWriter::DrawChar(uint16 unicode, const char* utf8, int16 size) REPORT(kDebug, -1, "encoding for %x not found!", (int)unicode); if (!found) { found = true; - REPORT(kError, fPage, "Could not find an encoding for character with unicode %d! Message is not repeated for other unicode values.", (int)unicode); + REPORT(kError, fPage, "Could not find an encoding for character " + "with unicode %d! Message is not repeated for other unicode " + "values.", (int)unicode); } *dest = 0; // paint a box (is 0 a box in MacRoman) or - return; // simply skip character + return; // simply skip character } } else { - REPORT(kDebug, -1, "macroman srcLen=%d destLen=%d dest= %d %d!", srcLen, destLen, (int)dest[0], (int)dest[1]); + REPORT(kDebug, -1, "macroman srcLen=%d destLen=%d dest= %d %d!", srcLen, + destLen, (int)dest[0], (int)dest[1]); } - - // Note we have to build the user defined encoding before it is used in PDF_find_font! + + // Note we have to build the user defined encoding before it is used in + // PDF_find_font! if (!MakesPDF()) return; - + int font; GetFontName(&fState->beFont, fontName, embed, encoding); - font = FindFont(fontName, embed, encoding); + font = FindFont(fontName, embed, encoding); if (font < 0) { - REPORT(kWarning, fPage, "**** PDF_findfont(%s) failed, back to default font", fontName); + REPORT(kWarning, fPage, "**** PDF_findfont(%s) failed, back to default " + "font", fontName); font = PDF_findfont(fPdf, "Helvetica", "macroman", 0); } fState->font = font; uint16 face = fState->beFont.Face(); - PDF_set_parameter(fPdf, "underline", (face & B_UNDERSCORE_FACE) != 0 ? "true" : "false"); - PDF_set_parameter(fPdf, "strikeout", (face & B_STRIKEOUT_FACE) != 0 ? "true" : "false"); - PDF_set_value(fPdf, "textrendering", (face & B_OUTLINED_FACE) != 0 ? 1 : 0); + PDF_set_parameter(fPdf, "underline", (face & B_UNDERSCORE_FACE) != 0 + ? "true" : "false"); + PDF_set_parameter(fPdf, "strikeout", (face & B_STRIKEOUT_FACE) != 0 + ? "true" : "false"); + PDF_set_value(fPdf, "textrendering", (face & B_OUTLINED_FACE) != 0 ? 1 : 0); PDF_setfont(fPdf, fState->font, scale(fState->beFont.Size())); @@ -465,7 +454,7 @@ PDFWriter::DrawChar(uint16 unicode, const char* utf8, int16 size) PDF_translate(fPdf, x, y); PDF_rotate(fPdf, rotation); PDF_set_text_pos(fPdf, 0, 0); - } else + } else PDF_set_text_pos(fPdf, x, y); PDF_show2(fPdf, dest, destLen); @@ -476,9 +465,9 @@ PDFWriter::DrawChar(uint16 unicode, const char* utf8, int16 size) } -// -------------------------------------------------- void -PDFWriter::ClipChar(BFont* font, const char* unicode, const char* utf8, int16 size, float width) +PDFWriter::ClipChar(BFont* font, const char* unicode, const char* utf8, + int16 size, float width) { BShape glyph; bool hasGlyph[1]; @@ -506,12 +495,12 @@ PDFWriter::ClipChar(BFont* font, const char* unicode, const char* utf8, int16 si glyph.LineTo(BPoint(o.right, o.bottom)); glyph.LineTo(BPoint(o.left, o.bottom)); glyph.Close(); - + glyph.MoveTo(BPoint(i.left, i.top)); glyph.LineTo(BPoint(i.left, i.bottom)); glyph.LineTo(BPoint(i.right, i.bottom)); glyph.LineTo(BPoint(i.right, i.top)); - glyph.Close(); + glyph.Close(); } BPoint p(fState->penX, fState->penY); @@ -523,12 +512,14 @@ PDFWriter::ClipChar(BFont* font, const char* unicode, const char* utf8, int16 si PopInternalState(); } -// -------------------------------------------------- -void -PDFWriter::DrawString(char *string, float escapement_nospace, float escapement_space) + +void +PDFWriter::DrawString(char *string, float escapementNoSpace, + float escapementSpace) { - REPORT(kDebug, fPage, "DrawString string=\"%s\", escapement_nospace=%f, escapement_space=%f, at %f, %f", \ - string, escapement_nospace, escapement_space, fState->penX, fState->penY); + REPORT(kDebug, fPage, "DrawString string=\"%s\", escapementNoSpace=%f, " + "escapementSpace=%f, at %f, %f", string, escapementNoSpace, + escapementSpace, fState->penX, fState->penY); if (IsDrawing()) { // text color is always the high color and not the pattern! @@ -541,14 +532,14 @@ PDFWriter::DrawString(char *string, float escapement_nospace, float escapement_s } else { ToUtf8(fState->beFont.Encoding()-1, string, utf8); } - + // convert string in UTF8 to unicode UCS2 BString unicode; - ToUnicode(utf8.String(), unicode); + ToUnicode(utf8.String(), unicode); // need font object to calculate width of utf8 code point BFont font = fState->beFont; font.SetEncoding(B_UNICODE_UTF8); - // constants to calculate position of next character + // constants to calculate position of next character const double rotation = DEGREE2RAD(fState->beFont.Rotation()); const bool rotate = rotation != 0.0; const double cos1 = rotate ? cos(rotation) : 1; @@ -569,14 +560,14 @@ PDFWriter::DrawString(char *string, float escapement_nospace, float escapement_s if (MakesPDF() && IsClipping()) { ClipChar(&font, (char*)u, c, s, w); } else { - DrawChar(u[0]*256+u[1], c, s); + DrawChar(u[0]*256+u[1], c, s); } - + // position of next character if (*(unsigned char*)c <= 0x20) { // should test if c is a white-space! - w += escapement_space; + w += escapementSpace; } else { - w += escapement_nospace; + w += escapementNoSpace; } fState->penX += w * cos1; @@ -588,36 +579,30 @@ PDFWriter::DrawString(char *string, float escapement_nospace, float escapement_s EndTransparency(); // text line processing (for non rotated text only!) - BPoint end(fState->penX, fState->penY); - BRect bounds; - font_height height; - + BPoint end(fState->penX, fState->penY); + BRect bounds; + font_height height; + font.GetHeight(&height); - - bounds.left = start.x; - bounds.right = end.x; - bounds.top = start.y - height.ascent; + + bounds.left = start.x; + bounds.right = end.x; + bounds.top = start.y - height.ascent; bounds.bottom = end.y + height.descent; - - TextSegment* segment = new TextSegment( - utf8.String(), start, - escapement_space, escapement_nospace, - &bounds, &font, pdfSystem()); - + + TextSegment* segment = new TextSegment(utf8.String(), start, escapementSpace, + escapementNoSpace, &bounds, &font, pdfSystem()); + fTextLine.Add(segment); - - if (IsDrawing()) { - } } -// -------------------------------------------------- bool PDFWriter::EmbedFont(const char* name) { static FontFile* cache = NULL; if (cache && strcmp(cache->Name(), name) == 0) return cache->Embed(); - + const int n = fFonts->Length(); for (int i = 0; i < n; i++) { FontFile* f = fFonts->At(i); diff --git a/src/add-ons/print/drivers/pdf/source/PDFWriter.cpp b/src/add-ons/print/drivers/pdf/source/PDFWriter.cpp index 0f0647f7e6..8c57db8a14 100644 --- a/src/add-ons/print/drivers/pdf/source/PDFWriter.cpp +++ b/src/add-ons/print/drivers/pdf/source/PDFWriter.cpp @@ -1,49 +1,30 @@ /* + * Copyright 2001-2009, Haiku, Inc. All Rights Reserved. + * Distributed under the terms of the MIT License. + * + * Authors: + * Philippe Houdoin + * Simon Gauvin + * Michael Pfeiffer + */ - PDFWriter.cpp - -Copyright (c) 2001, 2002 OpenBeOS. - -Authors: - Philippe Houdoin - Simon Gauvin - Michael Pfeiffer - -Based on: - - gdevbjc.c from Aladdin GhostScript - - LMDriver.cpp from Ryan Lockhart Lexmark 5/7xxxx BeOS driver - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - +/*! Based on: + - gdevbjc.c from Aladdin GhostScript + - LMDriver.cpp from Ryan Lockhart Lexmark 5/7xxxx BeOS driver */ -#include -#include // for memset() -#include +#include "PDFWriter.h" + #include +#include +#include +#include #include #include #include #include -#include "PDFWriter.h" #include "Bezier.h" #include "LinePathBuilder.h" #include "DrawShape.h" @@ -53,31 +34,29 @@ THE SOFTWARE. #include "XReferences.h" #include "Report.h" -// Constructor & destructor -// ------------------------ PDFWriter::PDFWriter() - : PrinterDriver() - , fTextLine(this) + : + PrinterDriver(), + fTextLine(this) { fFontSearchOrder[0] = japanese_encoding; fFontSearchOrder[1] = chinese_cns1_encoding; fFontSearchOrder[2] = chinese_gb1_encoding; fFontSearchOrder[3] = korean_encoding; - - fPage = 0; + + fPage = 0; fEmbedMaxFontSize = 250 * 1024; - fScreen = new BScreen(); - fFonts = NULL; - fBookmark = new Bookmark(this); - fXRefs = new XRefDefs(); - fXRefDests = NULL; + fScreen = new BScreen(); + fFonts = NULL; + fBookmark = new Bookmark(this); + fXRefs = new XRefDefs(); + fXRefDests = NULL; } -// -------------------------------------------------- PDFWriter::~PDFWriter() -{ +{ delete fScreen; delete fFonts; delete fBookmark; @@ -86,31 +65,26 @@ PDFWriter::~PDFWriter() } -#ifdef CODEWARRIOR - #pragma mark [Public methods] -#endif +// #pragma mark Public methods -// Public methods -// -------------- -// -------------------------------------------------- -status_t +status_t PDFWriter::PrintPage(int32 pageNumber, int32 pageCount) { - status_t status; - BRect r; - uint32 pictureCount; - BRect paperRect; - BRect printRect; - BRect *picRects; - BPoint *picPoints; - BRegion *picRegion; - BPicture **pictures; - uint32 i; - int32 orientation; - + status_t status; + BRect r; + uint32 pictureCount; + BRect paperRect; + BRect printRect; + BRect *picRects; + BPoint *picPoints; + BRegion *picRegion; + BPicture **pictures; + uint32 i; + int32 orientation; + status = B_OK; - + fPage = pageNumber; if (pageNumber == 1) { @@ -121,21 +95,23 @@ PDFWriter::PrintPage(int32 pageNumber, int32 pageCount) fImageCache.NextPass(); } } - + paperRect = JobMsg()->FindRect("paper_rect"); printRect = JobMsg()->FindRect("printable_rect"); if (B_OK != JobMsg()->FindInt32("orientation", &orientation)) orientation = 0; - if (orientation == 1) + if (orientation == 1) { printRect.Set(printRect.top, printRect.left, printRect.bottom, printRect.right); + } JobFile()->Read(&pictureCount, sizeof(uint32)); - pictures = (BPicture **) malloc(pictureCount * sizeof(BPicture *)); - picRects = (BRect *) malloc(pictureCount * sizeof(BRect)); - picPoints = (BPoint *) malloc(pictureCount * sizeof(BPoint)); + // TODO: error checking! + pictures = (BPicture **)malloc(pictureCount * sizeof(BPicture *)); + picRects = (BRect *)malloc(pictureCount * sizeof(BRect)); + picPoints = (BPoint *)malloc(pictureCount * sizeof(BPoint)); picRegion = new BRegion(); - + for (i = 0; i < pictureCount; i++) { JobFile()->Seek(40 + sizeof(off_t), SEEK_CUR); JobFile()->Read(&picPoints[i], sizeof(BPoint)); @@ -144,7 +120,7 @@ PDFWriter::PrintPage(int32 pageNumber, int32 pageCount) pictures[i]->Unflatten(JobFile()); picRegion->Include(picRects[i]); } - + r = picRegion->Frame(); delete picRegion; @@ -159,56 +135,55 @@ PDFWriter::PrintPage(int32 pageNumber, int32 pageCount) } EndPage(); } PDF_CATCH(fPdf) { - REPORT(kError, 0, PDF_get_errmsg(fPdf)); + REPORT(kError, 0, PDF_get_errmsg(fPdf)); } - + free(pictures); free(picRects); free(picPoints); - + return status; } -// -------------------------------------------------- -status_t -PDFWriter::BeginJob() +status_t +PDFWriter::BeginJob() { fLog = fopen("/tmp/pdf_writer.log", "w"); - + PDF_boot(); - fPdf = PDF_new2(_ErrorHandler, NULL, NULL, NULL, this); // set *this* as pdf cookie - if ( fPdf == NULL ) + fPdf = PDF_new2(_ErrorHandler, NULL, NULL, NULL, this); + // set *this* as pdf cookie + if (fPdf == NULL) return B_ERROR; // load font embedding settings fFonts = new Fonts(); fFonts->CollectFonts(); BMessage fonts; - if (B_OK == JobMsg()->FindMessage("fonts", &fonts)) { + if (B_OK == JobMsg()->FindMessage("fonts", &fonts)) fFonts->SetTo(&fonts); - } - + // set font search order - int j = 0; - font_encoding enc; - bool active; - - for (int i = 0; j < no_of_cjk_encodings && fFonts->GetCJKOrder(i, enc, active); i ++) { + int j = 0; + font_encoding enc; + bool active; + + for (int i = 0; j < no_of_cjk_encodings + && fFonts->GetCJKOrder(i, enc, active); i ++) { if (active) fFontSearchOrder[j++] = enc; } for (; j < no_of_cjk_encodings; j ++) { fFontSearchOrder[j] = invalid_encoding; } - + return InitWriter(); } -// -------------------------------------------------- -status_t -PDFWriter::EndJob() +status_t +PDFWriter::EndJob() { #ifdef DEBUG Report* r = Report::Instance(); @@ -228,48 +203,45 @@ PDFWriter::EndJob() } fprintf(fLog, " %s", rr->Label()); if (rr->Page() > 0) fprintf(fLog, " (Page %d)", (int)rr->Page()); - fprintf(fLog, ": %s\n", rr->Desc()); + fprintf(fLog, ": %s\n", rr->Desc()); } #endif fImageCache.Flush(); - + PDF_close(fPdf); REPORT(kDebug, 0, ">>>> PDF_close"); PDF_delete(fPdf); PDF_shutdown(); - + fclose(fLog); return B_OK; } -// -------------------------------------------------- -void -PDFWriter::SetAttribute(const char* name, const char* value) { - +void +PDFWriter::SetAttribute(const char* name, const char* value) +{ if (!name || !value) return; - - BFile * file = dynamic_cast(Transport()); - if (file) { + + BFile *file = dynamic_cast(Transport()); + if (file != NULL) file->WriteAttr(name, B_STRING_TYPE, 0, value, strlen(value) + 1); - } } -// -------------------------------------------------- -status_t +status_t PDFWriter::InitWriter() { - char buffer[512]; + char buffer[512]; BString s; fState = NULL; fStateDepth = 0; // Set MIME type explicit as we *do* know it's a PDF document - BFile * file = dynamic_cast(Transport()); + BFile *file = dynamic_cast(Transport()); if (file) BNodeInfo(file).SetType("application/pdf"); @@ -284,7 +256,7 @@ PDFWriter::InitWriter() */ fPDFVersion = kPDF13; - const char * compatibility; + const char *compatibility; if (JobMsg()->FindString("pdf_compatibility", &compatibility) == B_OK) { PDF_set_parameter(fPdf, "compatibility", compatibility); if (strcmp(compatibility, "1.3") == 0) fPDFVersion = kPDF13; @@ -304,13 +276,13 @@ PDFWriter::InitWriter() // set permissions BString permissions; - if (JobMsg()->FindString("permissions", &permissions) == B_OK && + if (JobMsg()->FindString("permissions", &permissions) == B_OK && permissions.Length() > 0) { PDF_set_parameter(fPdf, "permissions", permissions.String()); } */ - REPORT(kDebug, 0, ">>>> PDF_open_mem"); + REPORT(kDebug, 0, ">>>> PDF_open_mem"); PDF_open_mem(fPdf, _WriteData); // use callback to stream PDF document data to printer transport // pdflib scope: @@ -322,14 +294,15 @@ PDFWriter::InitWriter() bool setTitle = true; bool setCreator = true; if (JobMsg()->FindMessage("doc_info", &doc) == B_OK) { -#ifndef B_BEOS_VERSION_DANO +#ifndef B_BEOS_VERSION_DANO char *name; #else const char *name; -#endif +#endif uint32 type; int32 count; - for (int32 i = 0; doc.GetInfo(B_STRING_TYPE, i, &name, &type, &count) != B_BAD_INDEX; i++) { + for (int32 i = 0; doc.GetInfo(B_STRING_TYPE, i, &name, &type, &count) + != B_BAD_INDEX; i++) { if (type == B_STRING_TYPE) { BString value; if (doc.FindString(name, &value) == B_OK && value != "") { @@ -341,22 +314,26 @@ PDFWriter::InitWriter() } } BString s; - if (doc.FindString("Title", &s) == B_OK && s != "") setTitle = false; - if (doc.FindString("Creator", &s) == B_OK && s != "") setCreator = false; + if (doc.FindString("Title", &s) == B_OK && s != "") + setTitle = false; + if (doc.FindString("Creator", &s) == B_OK && s != "") + setCreator = false; } - - // find job title - if (setTitle && JobFile()->ReadAttr("_spool/Description", B_STRING_TYPE, 0, buffer, sizeof(buffer))) { + + // find job title + if (setTitle && JobFile()->ReadAttr("_spool/Description", B_STRING_TYPE, 0, + buffer, sizeof(buffer))) { SetAttribute("Title", buffer); ToPDFUnicode(buffer, s); PDF_set_info(fPdf, "Title", s.String()); } - + // find job creator - if (setCreator && JobFile()->ReadAttr("_spool/MimeType", B_STRING_TYPE, 0, buffer, sizeof(buffer))) { + if (setCreator && JobFile()->ReadAttr("_spool/MimeType", B_STRING_TYPE, 0, + buffer, sizeof(buffer))) { SetAttribute("Creator", buffer); ToPDFUnicode(buffer, s); PDF_set_info(fPdf, "Creator", s.String()); } - + int32 compression; if (JobMsg()->FindInt32("pdf_compression", &compression) == B_OK) { PDF_set_value(fPdf, "compress", compression); @@ -367,23 +344,33 @@ PDFWriter::InitWriter() PDF_set_parameter(fPdf, "fontwarning", "false"); // PDF_set_parameter(fPdf, "native-unicode", "true"); - REPORT(kDebug, 0, "Start of fonts declaration:"); + REPORT(kDebug, 0, "Start of fonts declaration:"); - PDF_set_parameter(fPdf, "Encoding", "t1enc0==/boot/home/config/settings/PDF Writer/t1enc0.enc"); - PDF_set_parameter(fPdf, "Encoding", "t1enc1==/boot/home/config/settings/PDF Writer/t1enc1.enc"); - PDF_set_parameter(fPdf, "Encoding", "t1enc2==/boot/home/config/settings/PDF Writer/t1enc2.enc"); - PDF_set_parameter(fPdf, "Encoding", "t1enc3==/boot/home/config/settings/PDF Writer/t1enc3.enc"); - PDF_set_parameter(fPdf, "Encoding", "t1enc4==/boot/home/config/settings/PDF Writer/t1enc4.enc"); + PDF_set_parameter(fPdf, "Encoding", + "t1enc0==/boot/home/config/settings/PDF Writer/t1enc0.enc"); + PDF_set_parameter(fPdf, "Encoding", + "t1enc1==/boot/home/config/settings/PDF Writer/t1enc1.enc"); + PDF_set_parameter(fPdf, "Encoding", + "t1enc2==/boot/home/config/settings/PDF Writer/t1enc2.enc"); + PDF_set_parameter(fPdf, "Encoding", + "t1enc3==/boot/home/config/settings/PDF Writer/t1enc3.enc"); + PDF_set_parameter(fPdf, "Encoding", + "t1enc4==/boot/home/config/settings/PDF Writer/t1enc4.enc"); - PDF_set_parameter(fPdf, "Encoding", "ttenc0==/boot/home/config/settings/PDF Writer/ttenc0.cpg"); - PDF_set_parameter(fPdf, "Encoding", "ttenc1==/boot/home/config/settings/PDF Writer/ttenc1.cpg"); - PDF_set_parameter(fPdf, "Encoding", "ttenc2==/boot/home/config/settings/PDF Writer/ttenc2.cpg"); - PDF_set_parameter(fPdf, "Encoding", "ttenc3==/boot/home/config/settings/PDF Writer/ttenc3.cpg"); - PDF_set_parameter(fPdf, "Encoding", "ttenc4==/boot/home/config/settings/PDF Writer/ttenc4.cpg"); + PDF_set_parameter(fPdf, "Encoding", + "ttenc0==/boot/home/config/settings/PDF Writer/ttenc0.cpg"); + PDF_set_parameter(fPdf, "Encoding", + "ttenc1==/boot/home/config/settings/PDF Writer/ttenc1.cpg"); + PDF_set_parameter(fPdf, "Encoding", + "ttenc2==/boot/home/config/settings/PDF Writer/ttenc2.cpg"); + PDF_set_parameter(fPdf, "Encoding", + "ttenc3==/boot/home/config/settings/PDF Writer/ttenc3.cpg"); + PDF_set_parameter(fPdf, "Encoding", + "ttenc4==/boot/home/config/settings/PDF Writer/ttenc4.cpg"); DeclareFonts(); - REPORT(kDebug, fPage, "End of fonts declaration."); + REPORT(kDebug, fPage, "End of fonts declaration."); // Links float width; @@ -391,23 +378,24 @@ PDFWriter::InitWriter() width = 1; } PDF_set_border_style(fPdf, "solid", width); - + if (JobMsg()->FindBool("create_web_links", &fCreateWebLinks) != B_OK) { fCreateWebLinks = false; } - // Bookmarks + // Bookmarks if (JobMsg()->FindBool("create_bookmarks", &fCreateBookmarks) != B_OK) { fCreateBookmarks = false; } if (fCreateBookmarks) { BString name; - if (JobMsg()->FindString("bookmark_definition_file", &name) == B_OK && LoadBookmarkDefinitions(name.String())) { + if (JobMsg()->FindString("bookmark_definition_file", &name) == B_OK + && LoadBookmarkDefinitions(name.String())) { } else { fCreateBookmarks = false; } - } + } // Cross References if (JobMsg()->FindBool("create_xrefs", &fCreateXRefs) != B_OK) { @@ -416,18 +404,18 @@ PDFWriter::InitWriter() if (fCreateXRefs) { BString name; - if (JobMsg()->FindString("xrefs_file", &name) == B_OK && LoadXRefsDefinitions(name.String())) { + if (JobMsg()->FindString("xrefs_file", &name) == B_OK + && LoadXRefsDefinitions(name.String())) { } else { REPORT(kError, 0, "Could not read xrefs file!"); fCreateXRefs = false; } - } + } return B_OK; } -// -------------------------------------------------- status_t PDFWriter::DeclareFonts() { @@ -443,10 +431,10 @@ PDFWriter::DeclareFonts() parameter_name = "FontAFM"; else if (strstr(f->Path(), ".pfm")) parameter_name = "FontPFM"; - else // should not reach here! - continue; + else // should not reach here! + continue; } -#ifndef __POWERPC__ +#ifndef __POWERPC__ snprintf(buffer, sizeof(buffer), "%s==%s", f->Name(), f->Path()); #else sprintf(buffer, "%s==%s", f->Name(), f->Path()); @@ -456,6 +444,7 @@ PDFWriter::DeclareFonts() return B_OK; } + bool PDFWriter::LoadBookmarkDefinitions(const char* name) { @@ -482,15 +471,14 @@ PDFWriter::LoadXRefsDefinitions(const char* name) } -// -------------------------------------------------- -status_t +status_t PDFWriter::BeginPage(BRect paperRect, BRect printRect) { float width = paperRect.Width() < 10 ? a4_width : paperRect.Width(); float height = paperRect.Height() < 10 ? a4_height : paperRect.Height(); - + fMode = kDrawingMode; - + ASSERT(fState == NULL); fState = new State(height, printRect.left, printRect.top); @@ -498,14 +486,14 @@ PDFWriter::BeginPage(BRect paperRect, BRect printRect) PDF_begin_page(fPdf, width, height); REPORT(kDebug, fPage, ">>>> PDF_begin_page [%f, %f]", width, height); - + if (MakesPDF()) PDF_initgraphics(fPdf); - + fState->penX = 0; fState->penY = 0; - // XXX should we clip to the printRect here? + // TODO: should we clip to the printRect here? PushState(); // so that fState->prev != NULL @@ -513,10 +501,9 @@ PDFWriter::BeginPage(BRect paperRect, BRect printRect) } -// -------------------------------------------------- -status_t +status_t PDFWriter::EndPage() -{ +{ fTextLine.Flush(); if (fCreateBookmarks) fBookmark->CreateBookmarks(); @@ -527,17 +514,15 @@ PDFWriter::EndPage() REPORT(kDebug, fPage, ">>>> PDF_end_page"); delete fState; fState = NULL; - + return B_OK; } -#ifdef CODEWARRIOR - #pragma mark [PDFlib callbacks] -#endif +// #pragma mark PDFlib callbacks -// -------------------------------------------------- -size_t + +size_t PDFWriter::WriteData(void *data, size_t size) { REPORT(kDebug, fPage, ">>>> WriteData %p, %ld", data, size); @@ -546,30 +531,26 @@ PDFWriter::WriteData(void *data, size_t size) } -// -------------------------------------------------- -void +void PDFWriter::ErrorHandler(int type, const char *msg) { REPORT(kError, fPage, "PDFlib %d: %s", type, msg); } -#ifdef CODEWARRIOR - #pragma mark [Generic drawing support routines] -#endif + +// #pragma mark Generic drawing support routines -// -------------------------------------------------- void -PDFWriter::PushInternalState() +PDFWriter::PushInternalState() { REPORT(kDebug, fPage, "PushInternalState"); fState = new State(fState); fStateDepth ++; } -// -------------------------------------------------- bool -PDFWriter::PopInternalState() +PDFWriter::PopInternalState() { REPORT(kDebug, fPage, "PopInternalState"); if (fStateDepth != 0) { @@ -584,9 +565,8 @@ PDFWriter::PopInternalState() } -// -------------------------------------------------- -PDFWriter::Transparency* -PDFWriter::FindTransparency(uint8 alpha) +PDFWriter::Transparency* +PDFWriter::FindTransparency(uint8 alpha) { const int n = fTransparencyCache.CountItems(); for (int i = 0; i < n; i ++) { @@ -596,31 +576,31 @@ PDFWriter::FindTransparency(uint8 alpha) return t; } } - + // create new handle for gstate char trans[256]; float a = (float)alpha/255.0; sprintf(trans, "opacitystroke=%f opacityfill=%f", a, a); - + volatile int handle = -1; PDF_TRY(fPdf) { handle = PDF_create_gstate(fPdf, trans); } PDF_CATCH(fPdf) { - REPORT(kError, 0, PDF_get_errmsg(fPdf)); + REPORT(kError, 0, PDF_get_errmsg(fPdf)); } REPORT(kDebug, fPage, trans); - + if (handle >= 0) { // store in cache Transparency* t = new Transparency(alpha, handle); fTransparencyCache.AddItem(t); return t; } - + return NULL; } -// -------------------------------------------------- + void PDFWriter::BeginTransparency() { @@ -628,8 +608,9 @@ PDFWriter::BeginTransparency() return; REPORT(kDebug, fPage, ">>> BeginTransparency"); - REPORT(kDebug, fPage, "current_color(%d, %d, %d, %d)", fState->currentColor.red, - fState->currentColor.green, fState->currentColor.blue, fState->currentColor.alpha); + REPORT(kDebug, fPage, "current_color(%d, %d, %d, %d)", + fState->currentColor.red, fState->currentColor.green, + fState->currentColor.blue, fState->currentColor.alpha); REPORT(kDebug, fPage, "drawing_mode %d alpha %d", (int)fState->drawingMode, (int)fState->currentColor.alpha); @@ -651,60 +632,62 @@ PDFWriter::BeginTransparency() fTransparencyStack.AddItem(NULL); } -// -------------------------------------------------- -void -PDFWriter::EndTransparency() + +void +PDFWriter::EndTransparency() { if (!SupportsOpacity() || !MakesPDF() || !IsDrawing()) return; REPORT(kDebug, fPage, "<<< EndTransparency"); int lastItem = fTransparencyStack.CountItems()-1; Transparency* t = fTransparencyStack.RemoveItem(lastItem); - + if (t != NULL) { PDF_restore(fPdf); } } -// -------------------------------------------------- -void -PDFWriter::SetColor(rgb_color color) + +void +PDFWriter::SetColor(rgb_color color) { if (!MakesPDF()) { // create PDFlib gstate handles - if (SupportsOpacity() && fState->currentColor.alpha != color.alpha && color.alpha < 255) { + if (SupportsOpacity() && fState->currentColor.alpha != color.alpha + && color.alpha < 255) { FindTransparency(color.alpha); } - } else if (fState->currentColor.red != color.red || - fState->currentColor.blue != color.blue || - fState->currentColor.green != color.green || + } else if (fState->currentColor.red != color.red || + fState->currentColor.blue != color.blue || + fState->currentColor.green != color.green || fState->currentColor.alpha != color.alpha) { fState->currentColor = color; float red = color.red / 255.0; float green = color.green / 255.0; float blue = color.blue / 255.0; PDF_setcolor(fPdf, "both", "rgb", red, green, blue, 0.0); - REPORT(kDebug, fPage, "set_color(%f, %f, %f, %f)", red, green, blue, color.alpha/255.0); + REPORT(kDebug, fPage, "set_color(%f, %f, %f, %f)", red, green, blue, + color.alpha / 255.0); } } -// -------------------------------------------------- int -PDFWriter::FindPattern() +PDFWriter::FindPattern() { // TODO: use hashtable instead of BList for fPatterns const int n = fPatterns.CountItems(); for (int i = 0; i < n; i ++) { Pattern* p = fPatterns.ItemAt(i); - if (p->Matches(fState->pattern0, fState->backgroundColor, fState->foregroundColor)) return p->patternId; + if (p->Matches(fState->pattern0, fState->backgroundColor, + fState->foregroundColor)) + return p->patternId; } return -1; } -// -------------------------------------------------- void -PDFWriter::CreatePattern() +PDFWriter::CreatePattern() { REPORT(kDebug, fPage, "CreatePattern"); #if 1 @@ -712,20 +695,20 @@ PDFWriter::CreatePattern() // pro: see con of bitmap pattern // con: not rendered (correctly) in BePDF with small zoom factor int pattern = PDF_begin_pattern(fPdf, 8, 8, 8, 8, 1); - + if (pattern == -1) { REPORT(kError, fPage, "CreatePattern could not create pattern"); return; } - + const int kPassForeground = 0; const int kPassBackground = 1; const int kNumPasses = 2; - + for (int pass = 0; pass < kNumPasses; pass ++) { float r, g, b; bool is_transparent; - + if (pass == kPassForeground) { r = fState->foregroundColor.red / 255.0; g = fState->foregroundColor.green / 255.0; @@ -737,11 +720,11 @@ PDFWriter::CreatePattern() b = fState->backgroundColor.blue / 255.0; is_transparent = fState->backgroundColor.alpha < 128; } - + PDF_setcolor(fPdf, "fill", "rgb", r, g, b, 0); - + if (is_transparent) continue; - + uint8* data = (uint8*)fState->pattern0.data; for (int8 y = 0; y <= 7; y ++, data ++) { uint8 d = *data; @@ -751,7 +734,7 @@ PDFWriter::CreatePattern() } else { // background if (pass != kPassBackground) continue; } - + // create rectangle for pixel float x1 = x + 1, y1 = y + 1; PDF_moveto(fPdf, x, y); @@ -760,10 +743,10 @@ PDFWriter::CreatePattern() PDF_lineto(fPdf, x1, y); PDF_closepath(fPdf); PDF_fill(fPdf); - } + } } } - + PDF_end_pattern(fPdf); #else @@ -771,7 +754,7 @@ PDFWriter::CreatePattern() // pro: BePDF renders pattern also with small zoom factor // con: BePDF omits mask during rendering BBitmap bm(BRect(0, 0, 7, 7), B_RGBA32); - + uint8* data = (uint8*)fState->pattern0.data; rgb_color h = fState->foregroundColor; rgb_color l = fState->backgroundColor; @@ -798,12 +781,13 @@ PDFWriter::CreatePattern() b[0] = l.blue; //fState->backgroundColor.blue; b[3] = l.alpha; //fState->backgroundColor.alpha; } - } + } } int mask, image; - - if (!GetImages(bm.Bounds(), 8, 8, bm.BytesPerRow(), bm.ColorSpace(), 0, bm.Bits(), &mask, &image)) { + + if (!GetImages(bm.Bounds(), 8, 8, bm.BytesPerRow(), bm.ColorSpace(), 0, + bm.Bits(), &mask, &image)) { return; } @@ -824,15 +808,15 @@ PDFWriter::CreatePattern() if (mask != -1) PDF_close_image(fPdf, mask); #endif #endif - - Pattern* p = new Pattern(fState->pattern0, fState->backgroundColor, fState->foregroundColor, pattern); + + Pattern* p = new Pattern(fState->pattern0, fState->backgroundColor, + fState->foregroundColor, pattern); fPatterns.AddItem(p); } -// -------------------------------------------------- void -PDFWriter::SetPattern() +PDFWriter::SetPattern() { REPORT(kDebug, fPage, "SetPattern (bitmap version)"); if (MakesPattern()) { @@ -849,9 +833,8 @@ PDFWriter::SetPattern() } -// -------------------------------------------------- -void -PDFWriter::StrokeOrClip() +void +PDFWriter::StrokeOrClip() { if (IsDrawing()) { PDF_stroke(fPdf); @@ -862,9 +845,8 @@ PDFWriter::StrokeOrClip() } -// -------------------------------------------------- -void -PDFWriter::FillOrClip() +void +PDFWriter::FillOrClip() { if (IsDrawing()) { PDF_fill(fPdf); @@ -874,9 +856,8 @@ PDFWriter::FillOrClip() } -// -------------------------------------------------- void -PDFWriter::Paint(bool stroke) +PDFWriter::Paint(bool stroke) { if (stroke) { StrokeOrClip(); @@ -886,9 +867,8 @@ PDFWriter::Paint(bool stroke) } -// -------------------------------------------------- -void -PDFWriter::SetColor() +void +PDFWriter::SetColor() { if (IsSame(fState->pattern0, B_SOLID_HIGH)) { SetColor(fState->foregroundColor); @@ -896,46 +876,47 @@ PDFWriter::SetColor() SetColor(fState->backgroundColor); } else { SetPattern(); - } + } } -#ifdef CODEWARRIOR - #pragma mark [Image drawing support routines] -#endif +// #pragma mark Image drawing support routines -// -------------------------------------------------- -int32 -PDFWriter::BytesPerPixel(int32 pixelFormat) +int32 +PDFWriter::BytesPerPixel(int32 pixelFormat) { switch (pixelFormat) { case B_RGB32: // fall through case B_RGB32_BIG: // fall through case B_RGBA32: // fall through - case B_RGBA32_BIG: return 4; + case B_RGBA32_BIG: + return 4; case B_RGB24_BIG: // fall through - case B_RGB24: return 3; + case B_RGB24: + return 3; case B_RGB16: // fall through case B_RGB16_BIG: // fall through case B_RGB15: // fall through case B_RGB15_BIG: // fall through case B_RGBA15: // fall through - case B_RGBA15_BIG: return 2; + case B_RGBA15_BIG: + return 2; case B_GRAY8: // fall through - case B_CMAP8: return 1; - case B_GRAY1: return 0; + case B_CMAP8: + return 1; + case B_GRAY1: + return 0; default: return -1; } } -// -------------------------------------------------- -bool -PDFWriter::HasAlphaChannel(int32 pixelFormat) +bool +PDFWriter::HasAlphaChannel(int32 pixelFormat) { switch (pixelFormat) { case B_RGB32: // fall through @@ -950,14 +931,17 @@ PDFWriter::HasAlphaChannel(int32 pixelFormat) case B_RGB15_BIG: // fall through case B_RGBA15: // fall through case B_RGBA15_BIG: // fall through - case B_CMAP8: return true; - default: return false; + case B_CMAP8: + return true; + default: + return false; } } -// -------------------------------------------------- + bool -PDFWriter::NeedsBPC1Mask(int32 pixelFormat) { +PDFWriter::NeedsBPC1Mask(int32 pixelFormat) +{ switch (pixelFormat) { // case B_RGB32: // fall through // case B_RGB32_BIG: // fall through @@ -965,85 +949,51 @@ PDFWriter::NeedsBPC1Mask(int32 pixelFormat) { case B_RGB15_BIG: // fall through case B_RGBA15: // fall through case B_RGBA15_BIG: // fall through - case B_CMAP8: return true; - default: return false; + case B_CMAP8: + return true; + default: + return false; }; } -// -------------------------------------------------- -bool -PDFWriter::IsTransparentRGB32(uint8* in) + +bool +PDFWriter::IsTransparentRGB32(uint8* in) { return *((uint32*)in) == B_TRANSPARENT_MAGIC_RGBA32; } -// -------------------------------------------------- -bool -PDFWriter::IsTransparentRGB32_BIG(uint8* in) +bool +PDFWriter::IsTransparentRGB32_BIG(uint8* in) { return *(uint32*)in == B_TRANSPARENT_MAGIC_RGBA32_BIG; } -// -------------------------------------------------- -bool -PDFWriter::IsTransparentRGBA32(uint8* in) +bool +PDFWriter::IsTransparentRGBA32(uint8* in) { return in[3] < 128 || IsTransparentRGB32(in); } -// -------------------------------------------------- -bool -PDFWriter::IsTransparentRGBA32_BIG(uint8* in) +bool +PDFWriter::IsTransparentRGBA32_BIG(uint8* in) { return in[0] < 127 || IsTransparentRGB32_BIG(in); } -/* -// -------------------------------------------------- -bool -PDFWriter::IsTransparentRGB24(uint8* in) -{ - return false; -} - -// -------------------------------------------------- -bool -PDFWriter::IsTransparentRGB24_BIG(uint8* in) -{ -} - - -// -------------------------------------------------- -bool -PDFWriter::IsTransparentRGB16(uint8* in) -{ - return false; -} - - -// -------------------------------------------------- -bool -PDFWriter::IsTransparentRGB16_BIG(uint8* in) -{ -} -*/ - - -// -------------------------------------------------- -bool -PDFWriter::IsTransparentRGB15(uint8* in) +bool +PDFWriter::IsTransparentRGB15(uint8* in) { return *((uint16*)in) == B_TRANSPARENT_MAGIC_RGBA15; } -// -------------------------------------------------- -bool -PDFWriter::IsTransparentRGB15_BIG(uint8* in) +bool +PDFWriter::IsTransparentRGB15_BIG(uint8* in) { // 01234567 01234567 // 00123434 01201234 @@ -1052,9 +1002,8 @@ PDFWriter::IsTransparentRGB15_BIG(uint8* in) } -// -------------------------------------------------- -bool -PDFWriter::IsTransparentRGBA15(uint8* in) +bool +PDFWriter::IsTransparentRGBA15(uint8* in) { // 01234567 01234567 // 01201234 00123434 @@ -1063,9 +1012,8 @@ PDFWriter::IsTransparentRGBA15(uint8* in) } -// -------------------------------------------------- -bool -PDFWriter::IsTransparentRGBA15_BIG(uint8* in) +bool +PDFWriter::IsTransparentRGBA15_BIG(uint8* in) { // 01234567 01234567 // 00123434 01201234 @@ -1074,53 +1022,36 @@ PDFWriter::IsTransparentRGBA15_BIG(uint8* in) } -// -------------------------------------------------- -bool -PDFWriter::IsTransparentCMAP8(uint8* in) +bool +PDFWriter::IsTransparentCMAP8(uint8* in) { return *in == B_TRANSPARENT_MAGIC_CMAP8; } -/* -// -------------------------------------------------- -bool -PDFWriter::IsTransparentGRAY8(uint8* in) -{ -} - - -// -------------------------------------------------- -bool -PDFWriter::IsTransparentGRAY1(uint8* in, int8 bit) -{ -} -*/ - - -// -------------------------------------------------- uint8 * -PDFWriter::CreateMask(BRect src, int32 bytesPerRow, int32 pixelFormat, int32 flags, void *data) +PDFWriter::CreateMask(BRect src, int32 bytesPerRow, int32 pixelFormat, + int32 flags, void *data) { uint8 *in; uint8 *inRow; int32 x, y; - + uint8 *mask; uint8 *maskRow; uint8 *out; int32 maskWidth; uint8 shift; bool alpha; - int32 bpp; + int32 bpp; - bpp = BytesPerPixel(pixelFormat); - if (bpp < 0) + bpp = BytesPerPixel(pixelFormat); + if (bpp < 0) return NULL; - + int32 width = src.IntegerWidth() + 1; int32 height = src.IntegerHeight() + 1; - + // Image Mask inRow = (uint8 *) data; inRow += bytesPerRow * (int) src.top + bpp * (int) src.left; @@ -1129,13 +1060,13 @@ PDFWriter::CreateMask(BRect src, int32 bytesPerRow, int32 pixelFormat, int32 fla maskRow = mask = new uint8[maskWidth * height]; memset(mask, 0, maskWidth*height); alpha = false; - + for (y = height; y > 0; y--) { in = inRow; out = maskRow; shift = 7; - - bool a = false; + + bool a = false; for (x = width; x > 0; x-- ) { // For each pixel @@ -1155,17 +1086,19 @@ PDFWriter::CreateMask(BRect src, int32 bytesPerRow, int32 pixelFormat, int32 fla case B_CMAP8: a = IsTransparentCMAP8(in); break; //case B_GRAY8: a = IsTransparentGRAY8(in); break; //case B_GRAY1: a = false; break; - default: a = false; // should not reach here - REPORT(kDebug, fPage, "CreateMask: non transparentable pixelFormat"); + default: + a = false; // should not reach here + REPORT(kDebug, fPage, + "CreateMask: non transparentable pixelFormat"); } if (a) { out[0] |= (1 << shift); alpha = true; } - // next pixel + // next pixel if (shift == 0) out ++; - shift = (shift + 7) & 0x07; + shift = (shift + 7) & 0x07; in += bpp; } @@ -1173,7 +1106,7 @@ PDFWriter::CreateMask(BRect src, int32 bytesPerRow, int32 pixelFormat, int32 fla inRow += bytesPerRow; maskRow += maskWidth; } - + if (!alpha) { delete []mask; mask = NULL; @@ -1182,46 +1115,45 @@ PDFWriter::CreateMask(BRect src, int32 bytesPerRow, int32 pixelFormat, int32 fla } -// -------------------------------------------------- -uint8 +uint8 PDFWriter::AlphaFromRGBA32(uint8* in) { return in[2]; } -// -------------------------------------------------- -uint8 +uint8 PDFWriter::AlphaFromRGBA32_BIG(uint8* in) { return in[0]; } -// -------------------------------------------------- uint8 * -PDFWriter::CreateSoftMask(BRect src, int32 bytesPerRow, int32 pixelFormat, int32 flags, void *data) +PDFWriter::CreateSoftMask(BRect src, int32 bytesPerRow, int32 pixelFormat, + int32 flags, void *data) { static bool errorReported = false; uint8 *in; uint8 *inRow; int32 x, y; - + uint8 *mask; uint8 *maskRow; uint8 *out; bool alpha; - int32 bpp; + int32 bpp; +// TODO: CreateSoftMask??? return NULL; - bpp = BytesPerPixel(pixelFormat); - if (bpp < 0) + bpp = BytesPerPixel(pixelFormat); + if (bpp < 0) return NULL; - - int32 width = src.IntegerWidth() + 1; - int32 height = src.IntegerHeight() + 1; - + + int32 width = src.IntegerWidth() + 1; + int32 height = src.IntegerHeight() + 1; + // Image Mask inRow = (uint8 *) data; inRow += bytesPerRow * (int) src.top + bpp * (int) src.left; @@ -1230,27 +1162,31 @@ PDFWriter::CreateSoftMask(BRect src, int32 bytesPerRow, int32 pixelFormat, int32 maskRow = mask = new uint8[width * height]; memset(mask, 0, width * height); alpha = false; - + for (y = height; y > 0; y--) { in = inRow; out = maskRow; - - uint8 a; + + uint8 a; for (x = width; x > 0; x-- ) { // For each pixel switch (pixelFormat) { case B_RGB32: // fall through - case B_RGBA32: a = AlphaFromRGBA32(in); + case B_RGBA32: + a = AlphaFromRGBA32(in); break; case B_RGB32_BIG: // fall through - case B_RGBA32_BIG: a = AlphaFromRGBA32_BIG(in); + case B_RGBA32_BIG: + a = AlphaFromRGBA32_BIG(in); break; - default: a = 255; // should not reach here + default: + a = 255; // should not reach here if (!errorReported) { - REPORT(kDebug, fPage, "CreateSoftMask: non transparentable pixelFormat"); + REPORT(kDebug, fPage, + "CreateSoftMask: non transparentable pixelFormat"); errorReported = true; } } @@ -1259,7 +1195,7 @@ PDFWriter::CreateSoftMask(BRect src, int32 bytesPerRow, int32 pixelFormat, int32 if (a != 255) { alpha = true; } - // next pixel + // next pixel out ++; in += bpp; } @@ -1268,7 +1204,7 @@ PDFWriter::CreateSoftMask(BRect src, int32 bytesPerRow, int32 pixelFormat, int32 inRow += bytesPerRow; maskRow += width; } - + if (!alpha) { delete []mask; mask = NULL; @@ -1277,24 +1213,21 @@ PDFWriter::CreateSoftMask(BRect src, int32 bytesPerRow, int32 pixelFormat, int32 } -// -------------------------------------------------- -void +void PDFWriter::ConvertFromRGB32(uint8* in, uint8 *out) { *((rgb_color*)out) = *((rgb_color*)in); } -// -------------------------------------------------- -void +void PDFWriter::ConvertFromRGBA32(uint8* in, uint8 *out) { *((rgb_color*)out) = *((rgb_color*)in); } -// -------------------------------------------------- -void +void PDFWriter::ConvertFromRGB24(uint8* in, uint8 *out) { out[0] = in[0]; @@ -1304,8 +1237,7 @@ PDFWriter::ConvertFromRGB24(uint8* in, uint8 *out) } -// -------------------------------------------------- -void +void PDFWriter::ConvertFromRGB16(uint8* in, uint8 *out) { // 01234567 01234567 @@ -1318,8 +1250,7 @@ PDFWriter::ConvertFromRGB16(uint8* in, uint8 *out) } -// -------------------------------------------------- -void +void PDFWriter::ConvertFromRGB15(uint8* in, uint8 *out) { // 01234567 01234567 @@ -1332,8 +1263,7 @@ PDFWriter::ConvertFromRGB15(uint8* in, uint8 *out) } -// -------------------------------------------------- -void +void PDFWriter::ConvertFromRGBA15(uint8* in, uint8 *out) { // 01234567 01234567 @@ -1346,8 +1276,7 @@ PDFWriter::ConvertFromRGBA15(uint8* in, uint8 *out) } -// -------------------------------------------------- -void +void PDFWriter::ConvertFromCMAP8(uint8* in, uint8 *out) { rgb_color c = fScreen->ColorForIndex(in[0]); @@ -1358,8 +1287,7 @@ PDFWriter::ConvertFromCMAP8(uint8* in, uint8 *out) } -// -------------------------------------------------- -void +void PDFWriter::ConvertFromGRAY8(uint8* in, uint8 *out) { out[0] = in[0]; @@ -1369,8 +1297,7 @@ PDFWriter::ConvertFromGRAY8(uint8* in, uint8 *out) } -// -------------------------------------------------- -void +void PDFWriter::ConvertFromGRAY1(uint8* in, uint8 *out, int8 bit) { uint8 gray = (in[0] & (1 << bit)) ? 255 : 0; @@ -1381,8 +1308,7 @@ PDFWriter::ConvertFromGRAY1(uint8* in, uint8 *out, int8 bit) } -// -------------------------------------------------- -void +void PDFWriter::ConvertFromRGB32_BIG(uint8* in, uint8 *out) { out[0] = in[3]; @@ -1392,8 +1318,7 @@ PDFWriter::ConvertFromRGB32_BIG(uint8* in, uint8 *out) } -// -------------------------------------------------- -void +void PDFWriter::ConvertFromRGBA32_BIG(uint8* in, uint8 *out) { out[0] = in[3]; @@ -1403,8 +1328,7 @@ PDFWriter::ConvertFromRGBA32_BIG(uint8* in, uint8 *out) } -// -------------------------------------------------- -void +void PDFWriter::ConvertFromRGB24_BIG(uint8* in, uint8 *out) { out[0] = in[2]; @@ -1414,8 +1338,7 @@ PDFWriter::ConvertFromRGB24_BIG(uint8* in, uint8 *out) } -// -------------------------------------------------- -void +void PDFWriter::ConvertFromRGB16_BIG(uint8* in, uint8 *out) { // 01234567 01234567 @@ -1428,8 +1351,7 @@ PDFWriter::ConvertFromRGB16_BIG(uint8* in, uint8 *out) } -// -------------------------------------------------- -void +void PDFWriter::ConvertFromRGB15_BIG(uint8* in, uint8 *out) { // 01234567 01234567 @@ -1442,8 +1364,7 @@ PDFWriter::ConvertFromRGB15_BIG(uint8* in, uint8 *out) } -// -------------------------------------------------- -void +void PDFWriter::ConvertFromRGBA15_BIG(uint8* in, uint8 *out) { // 01234567 01234567 @@ -1456,10 +1377,10 @@ PDFWriter::ConvertFromRGBA15_BIG(uint8* in, uint8 *out) } -// -------------------------------------------------- -// Convert and clip bits to colorspace B_RGBA32 +//! Convert and clip bits to colorspace B_RGBA32 BBitmap * -PDFWriter::ConvertBitmap(BRect src, int32 bytesPerRow, int32 pixelFormat, int32 flags, void *data) +PDFWriter::ConvertBitmap(BRect src, int32 bytesPerRow, int32 pixelFormat, + int32 flags, void *data) { uint8 *in; uint8 *inLeft; @@ -1467,15 +1388,15 @@ PDFWriter::ConvertBitmap(BRect src, int32 bytesPerRow, int32 pixelFormat, int32 uint8 *outLeft; int32 x, y; int8 bit; - int32 bpp = 4; + int32 bpp = 4; - bpp = BytesPerPixel(pixelFormat); - if (bpp < 0) + bpp = BytesPerPixel(pixelFormat); + if (bpp < 0) return NULL; int32 width = src.IntegerWidth(); int32 height = src.IntegerHeight(); - BBitmap * bm = new BBitmap(BRect(0, 0, width, height), B_RGB32); + BBitmap *bm = new BBitmap(BRect(0, 0, width, height), B_RGB32); if (!bm->IsValid()) { delete bm; REPORT(kError, fPage, "BBitmap constructor failed"); @@ -1483,9 +1404,9 @@ PDFWriter::ConvertBitmap(BRect src, int32 bytesPerRow, int32 pixelFormat, int32 } inLeft = (uint8 *)data; - inLeft += bytesPerRow * (int)src.top + bpp * (int)src.left; + inLeft += bytesPerRow * (int)src.top + bpp * (int)src.left; outLeft = (uint8*)bm->Bits(); - + for (y = height; y >= 0; y--) { in = inLeft; out = outLeft; @@ -1501,10 +1422,10 @@ PDFWriter::ConvertBitmap(BRect src, int32 bytesPerRow, int32 pixelFormat, int32 case B_RGBA15: ConvertFromRGBA15(in, out); break; case B_CMAP8: ConvertFromCMAP8(in, out); break; case B_GRAY8: ConvertFromGRAY8(in, out); break; - case B_GRAY1: + case B_GRAY1: bit = x & 7; ConvertFromGRAY1(in, out, bit); - if (bit == 7) in ++; + if (bit == 7) in ++; break; case B_RGB32_BIG: ConvertFromRGB32_BIG(in, out); break; case B_RGBA32_BIG: ConvertFromRGBA32_BIG(in, out); break; @@ -1522,14 +1443,14 @@ PDFWriter::ConvertBitmap(BRect src, int32 bytesPerRow, int32 pixelFormat, int32 inLeft += bytesPerRow; outLeft += bm->BytesPerRow(); } - + return bm; } -// -------------------------------------------------- -bool -PDFWriter::StoreTranslatorBitmap(BBitmap *bitmap, const char *filename, uint32 type) +bool +PDFWriter::StoreTranslatorBitmap(BBitmap *bitmap, const char *filename, + uint32 type) { BTranslatorRoster *roster = BTranslatorRoster::Default(); if (!roster) { @@ -1550,10 +1471,10 @@ PDFWriter::StoreTranslatorBitmap(BBitmap *bitmap, const char *filename, uint32 t LOG((fLog, " name = %s\n", info.name)); LOG((fLog, " MIME = %s\n", info.MIME)); #endif - + int32 numInfo; translator_info *tInfo = NULL; - if (roster->GetTranslators(&stream, NULL, &tInfo, &numInfo, + if (roster->GetTranslators(&stream, NULL, &tInfo, &numInfo, info.type, NULL, type) == B_OK) { // #ifdef DEBUG @@ -1576,7 +1497,7 @@ PDFWriter::StoreTranslatorBitmap(BBitmap *bitmap, const char *filename, uint32 t } else { LOG((fLog, "ERROR: could not get configuration message %d\n", s)); } - + info = tInfo[0]; info.quality = quality; delete []tInfo; @@ -1587,19 +1508,20 @@ PDFWriter::StoreTranslatorBitmap(BBitmap *bitmap, const char *filename, uint32 t */ BFile file(filename, B_CREATE_FILE | B_WRITE_ONLY | B_ERASE_FILE); bool res = roster->Translate(&stream, NULL /*i*/, NULL, &file, type) == B_OK; - BBitmap *bm = NULL; + BBitmap *bm = NULL; // detach bitmap so BBitmapStream destructor does not delete our bitmap! - stream.DetachBitmap(&bm); + stream.DetachBitmap(&bm); ASSERT(bm == bitmap); return res; } -// -------------------------------------------------- -bool -PDFWriter::GetImages(BRect src, int32 /*width*/, int32 /*height*/, int32 bytesPerRow, int32 pixelFormat, - int32 flags, void *data, int* maskId, int* image) + +bool +PDFWriter::GetImages(BRect src, int32 /*width*/, int32 /*height*/, + int32 bytesPerRow, int32 pixelFormat, int32 flags, void *data, int* maskId, + int* image) { - uint8 *mask = NULL; + uint8 *mask = NULL; *maskId = -1; int32 width = src.IntegerWidth() + 1; @@ -1607,7 +1529,7 @@ PDFWriter::GetImages(BRect src, int32 /*width*/, int32 /*height*/, int32 bytesPe int length = 0; int bpc = 0; - + if (HasAlphaChannel(pixelFormat)) { if (NeedsBPC1Mask(pixelFormat) || !SupportsSoftMask()) { int32 w = (width+7)/8; @@ -1622,7 +1544,7 @@ PDFWriter::GetImages(BRect src, int32 /*width*/, int32 /*height*/, int32 bytesPe REPORT(kDebug, fPage, "SoftMask created mask = %p", mask); } } - + if (mask) { // PDFlib deprecated: // *maskId = PDF_open_image(fPdf, "raw", "memory", (const char *) mask, length, width, height, 1, bpc, "mask"); @@ -1631,7 +1553,7 @@ PDFWriter::GetImages(BRect src, int32 /*width*/, int32 /*height*/, int32 bytesPe #else BString options; PDF_create_pvf(fPdf, "mask", 0, mask, length, NULL); - options << "width " << width << " height " << height << " components 1 bpc " << bpc; + options << "width " << width << " height " << height << " components 1 bpc " << bpc; *maskId = PDF_load_image(fPdf, "raw", "mask", 0, options.String()); PDF_delete_pvf(fPdf, "mask", 0); #endif @@ -1652,7 +1574,7 @@ PDFWriter::GetImages(BRect src, int32 /*width*/, int32 /*height*/, int32 bytesPe delete bm; #else char *pdfLibFormat = "png"; - char *bitmapFileName = "/tmp/pdfwriter.png"; + char *bitmapFileName = "/tmp/pdfwriter.png"; const uint32 beosFormat = B_PNG_FORMAT; if (!StoreTranslatorBitmap(bm, bitmapFileName, beosFormat)) { @@ -1665,7 +1587,7 @@ PDFWriter::GetImages(BRect src, int32 /*width*/, int32 /*height*/, int32 bytesPe } delete bm; - *image = PDF_open_image_file(fPdf, pdfLibFormat, bitmapFileName, + *image = PDF_open_image_file(fPdf, pdfLibFormat, bitmapFileName, *maskId == -1 ? "" : "masked", *maskId == -1 ? 0 : *maskId); #endif @@ -1673,38 +1595,35 @@ PDFWriter::GetImages(BRect src, int32 /*width*/, int32 /*height*/, int32 bytesPe } -#ifdef CODEWARRIOR - #pragma mark -- BPicture playback handlers -#endif +// #pragma mark BPicture playback handlers -// -------------------------------------------------- -void PDFWriter::Op(int number) +void +PDFWriter::Op(int number) { REPORT(kError, fPage, "Unhandled operand %d", number); } -// -------------------------------------------------- -void +void PDFWriter::MovePenBy(BPoint delta) { - REPORT(kDebug, fPage, "MovePenBy delta=[%f, %f]", \ - delta.x, delta.y); + REPORT(kDebug, fPage, "MovePenBy delta=[%f, %f]", delta.x, delta.y); fState->penX += delta.x; fState->penY += delta.y; } -// -------------------------------------------------- void PDFWriter::StrokeLine(BPoint start, BPoint end) { - REPORT(kDebug, fPage, "StrokeLine start=[%f, %f], end=[%f, %f]", \ - start.x, start.y, end.x, end.y); + REPORT(kDebug, fPage, "StrokeLine start=[%f, %f], end=[%f, %f]", + start.x, start.y, end.x, end.y); + + SetColor(); + if (!MakesPDF()) + return; - SetColor(); - if (!MakesPDF()) return; if (IsClipping()) { BShape shape; shape.MoveTo(start); @@ -1720,15 +1639,16 @@ PDFWriter::StrokeLine(BPoint start, BPoint end) } -// -------------------------------------------------- -void +void PDFWriter::StrokeRect(BRect rect) { - REPORT(kDebug, fPage, "StrokeRect rect=[%f, %f, %f, %f]", \ - rect.left, rect.top, rect.right, rect.bottom); + REPORT(kDebug, fPage, "StrokeRect rect=[%f, %f, %f, %f]", + rect.left, rect.top, rect.right, rect.bottom); + + SetColor(); + if (!MakesPDF()) + return; - SetColor(); - if (!MakesPDF()) return; if (IsClipping()) { BShape shape; shape.MoveTo(BPoint(rect.left, rect.top)); @@ -1739,47 +1659,52 @@ PDFWriter::StrokeRect(BRect rect) StrokeShape(&shape); } else { BeginTransparency(); - PDF_rect(fPdf, tx(rect.left), ty(rect.bottom), scale(rect.Width()), scale(rect.Height())); + PDF_rect(fPdf, tx(rect.left), ty(rect.bottom), scale(rect.Width()), + scale(rect.Height())); StrokeOrClip(); EndTransparency(); } } -// -------------------------------------------------- -void +void PDFWriter::FillRect(BRect rect) { - REPORT(kDebug, fPage, "FillRect rect=[%f, %f, %f, %f]", \ - rect.left, rect.top, rect.right, rect.bottom); + REPORT(kDebug, fPage, "FillRect rect=[%f, %f, %f, %f]", + rect.left, rect.top, rect.right, rect.bottom); + + SetColor(); + if (!MakesPDF()) + return; - SetColor(); - if (!MakesPDF()) return; BeginTransparency(); - PDF_rect(fPdf, tx(rect.left), ty(rect.bottom), scale(rect.Width()), scale(rect.Height())); + PDF_rect(fPdf, tx(rect.left), ty(rect.bottom), scale(rect.Width()), + scale(rect.Height())); FillOrClip(); EndTransparency(); } -// -------------------------------------------------- -// The quarter ellipses in the corners of the rectangle are -// approximated with bezier curves. -// The constant 0.555... is taken from gobeProductive. -void -PDFWriter::PaintRoundRect(BRect rect, BPoint radii, bool stroke) { +/*! The quarter ellipses in the corners of the rectangle are + approximated with bezier curves. + The constant 0.555... is taken from gobeProductive. +*/ +void +PDFWriter::PaintRoundRect(BRect rect, BPoint radii, bool stroke) +{ SetColor(); - if (!MakesPDF()) return; - + if (!MakesPDF()) + return; + BPoint center; - + float sx = radii.x; float sy = radii.y; char str[256]; sprintf(str, "PaintRoundRect sx %f sy %f", sx, sy); REPORT(kDebug, fPage, str); - + float ax = sx; float bx = 0.5555555555555 * sx; float ay = sy; @@ -1795,7 +1720,7 @@ PDFWriter::PaintRoundRect(BRect rect, BPoint radii, bool stroke) { BPoint(center.x - bx, center.y - ay), BPoint(center.x , center.y - ay)}; shape.BezierTo(a); - + center.x = rect.right - sx; shape.LineTo(BPoint(center.x, center.y - ay)); @@ -1804,58 +1729,58 @@ PDFWriter::PaintRoundRect(BRect rect, BPoint radii, bool stroke) { BPoint(center.x + ax, center.y - by), BPoint(center.x + ax, center.y)}; shape.BezierTo(b); - + center.y = rect.bottom - sy; - shape.LineTo(BPoint(center.x + sx, center.y)); + shape.LineTo(BPoint(center.x + sx, center.y)); BPoint c[3] = { BPoint(center.x + ax, center.y + by), BPoint(center.x + bx, center.y + ay), BPoint(center.x , center.y + ay)}; shape.BezierTo(c); - - center.x = rect.left + sx; + + center.x = rect.left + sx; shape.LineTo(BPoint(center.x, center.y + ay)); BPoint d[3] = { BPoint(center.x - bx, center.y + ay), BPoint(center.x - ax, center.y + by), BPoint(center.x - ax, center.y)}; - shape.BezierTo(d); + shape.BezierTo(d); shape.Close(); - + PaintShape(&shape, stroke); } -// -------------------------------------------------- -void +void PDFWriter::StrokeRoundRect(BRect rect, BPoint radii) { - REPORT(kDebug, fPage, "StrokeRoundRect center=[%f, %f, %f, %f], radii=[%f, %f]", \ - rect.left, rect.top, rect.right, rect.bottom, radii.x, radii.y); + REPORT(kDebug, fPage, "StrokeRoundRect center=[%f, %f, %f, %f], " + "radii=[%f, %f]", rect.left, rect.top, rect.right, rect.bottom, radii.x, + radii.y); PaintRoundRect(rect, radii, kStroke); } -// -------------------------------------------------- -void +void PDFWriter::FillRoundRect(BRect rect, BPoint radii) { - REPORT(kDebug, fPage, "FillRoundRect rect=[%f, %f, %f, %f], radii=[%f, %f]", \ - rect.left, rect.top, rect.right, rect.bottom, radii.x, radii.y); + REPORT(kDebug, fPage, "FillRoundRect rect=[%f, %f, %f, %f], radii=[%f, %f]", + rect.left, rect.top, rect.right, rect.bottom, radii.x, radii.y); PaintRoundRect(rect, radii, kFill); } -// -------------------------------------------------- -void -PDFWriter::StrokeBezier(BPoint *control) +void +PDFWriter::StrokeBezier(BPoint *control) { REPORT(kDebug, fPage, "StrokeBezier"); SetColor(); - if (!MakesPDF()) return; + if (!MakesPDF()) + return; + BShape shape; shape.MoveTo(control[0]); shape.BezierTo(&control[1]); @@ -1863,8 +1788,7 @@ PDFWriter::StrokeBezier(BPoint *control) } -// -------------------------------------------------- -void +void PDFWriter::FillBezier(BPoint *control) { REPORT(kDebug, fPage, "FillBezier"); @@ -1872,18 +1796,19 @@ PDFWriter::FillBezier(BPoint *control) if (!MakesPDF()) return; PDF_moveto(fPdf, tx(control[0].x), ty(control[0].y)); PDF_curveto(fPdf, tx(control[1].x), ty(control[1].y), - tx(control[2].x), ty(control[2].y), - tx(control[3].x), ty(control[3].y)); + tx(control[2].x), ty(control[2].y), tx(control[3].x), ty(control[3].y)); PDF_closepath(fPdf); FillOrClip(); } -// -------------------------------------------------- -// Note the pen size is also scaled! -// We should approximate it with bezier curves too! +/*! Note the pen size is also scaled! + We should approximate it with bezier curves too! +*/ void -PDFWriter::PaintArc(BPoint center, BPoint radii, float startTheta, float arcTheta, int stroke) { +PDFWriter::PaintArc(BPoint center, BPoint radii, float startTheta, + float arcTheta, int stroke) +{ float sx = scale(radii.x); float sy = scale(radii.y); float smax = sx > sy ? sx : sy; @@ -1891,43 +1816,44 @@ PDFWriter::PaintArc(BPoint center, BPoint radii, float startTheta, float arcThet SetColor(); if (!MakesPDF()) return; if (IsClipping()); // TODO clip to line path - + PDF_save(fPdf); PDF_scale(fPdf, sx, sy); PDF_setlinewidth(fPdf, fState->penSize / smax); - PDF_arc(fPdf, tx(center.x) / sx, ty(center.y) / sy, 1, startTheta, startTheta + arcTheta); + PDF_arc(fPdf, tx(center.x) / sx, ty(center.y) / sy, 1, startTheta, + startTheta + arcTheta); Paint(stroke); PDF_restore(fPdf); } -// -------------------------------------------------- void -PDFWriter::StrokeArc(BPoint center, BPoint radii, float startTheta, float arcTheta) +PDFWriter::StrokeArc(BPoint center, BPoint radii, float startTheta, + float arcTheta) { - REPORT(kDebug, fPage, "StrokeArc center=[%f, %f], radii=[%f, %f], startTheta=%f, arcTheta=%f", \ - center.x, center.y, radii.x, radii.y, startTheta, arcTheta); + REPORT(kDebug, fPage, "StrokeArc center=[%f, %f], radii=[%f, %f], " + "startTheta=%f, arcTheta=%f", center.x, center.y, radii.x, radii.y, + startTheta, arcTheta); PaintArc(center, radii, startTheta, arcTheta, true); } -// -------------------------------------------------- -void +void PDFWriter::FillArc(BPoint center, BPoint radii, float startTheta, float arcTheta) { - REPORT(kDebug, fPage, "FillArc center=[%f, %f], radii=[%f, %f], startTheta=%f, arcTheta=%f", \ - center.x, center.y, radii.x, radii.y, startTheta, arcTheta); + REPORT(kDebug, fPage, "FillArc center=[%f, %f], radii=[%f, %f], " + "startTheta=%f, arcTheta=%f", center.x, center.y, radii.x, radii.y, + startTheta, arcTheta); PaintArc(center, radii, startTheta, arcTheta, false); } -// -------------------------------------------------- void PDFWriter::PaintEllipse(BPoint center, BPoint radii, bool stroke) { float sx = radii.x; float sy = radii.y; - + float ax = sx; float bx = 0.5555555555555 * sx; float ay = sy; @@ -1940,7 +1866,7 @@ PDFWriter::PaintEllipse(BPoint center, BPoint radii, bool stroke) shape.MoveTo(BPoint(center.x - ax, center.y)); - BPoint a[3] = { + BPoint a[3] = { BPoint(center.x - ax, center.y - by), BPoint(center.x - bx, center.y - ay), BPoint(center.x , center.y - ay) }; @@ -1950,7 +1876,7 @@ PDFWriter::PaintEllipse(BPoint center, BPoint radii, bool stroke) BPoint(center.x + bx, center.y - ay), BPoint(center.x + ax, center.y - by), BPoint(center.x + ax, center.y)}; - shape.BezierTo(b); + shape.BezierTo(b); BPoint c[3] = { BPoint(center.x + ax, center.y + by), @@ -1963,47 +1889,47 @@ PDFWriter::PaintEllipse(BPoint center, BPoint radii, bool stroke) BPoint(center.x - ax, center.y + by), BPoint(center.x - ax, center.y)}; shape.BezierTo(d); - + shape.Close(); - PaintShape(&shape, stroke); + PaintShape(&shape, stroke); } -// -------------------------------------------------- + void PDFWriter::StrokeEllipse(BPoint center, BPoint radii) { - REPORT(kDebug, fPage, "StrokeEllipse center=[%f, %f], radii=[%f, %f]", \ - center.x, center.y, radii.x, radii.y); + REPORT(kDebug, fPage, "StrokeEllipse center=[%f, %f], radii=[%f, %f]", + center.x, center.y, radii.x, radii.y); PaintEllipse(center, radii, true); } -// -------------------------------------------------- void PDFWriter::FillEllipse(BPoint center, BPoint radii) { - REPORT(kDebug, fPage, "FillEllipse center=[%f, %f], radii=[%f, %f]", \ - center.x, center.y, radii.x, radii.y); + REPORT(kDebug, fPage, "FillEllipse center=[%f, %f], radii=[%f, %f]", + center.x, center.y, radii.x, radii.y); PaintEllipse(center, radii, false); } -// -------------------------------------------------- -void +void PDFWriter::StrokePolygon(int32 numPoints, BPoint *points, bool isClosed) { - int32 i; - float x0, y0; - REPORT(kDebug, fPage, "StrokePolygon numPoints=%ld, isClosed=%d\npoints=", \ - numPoints, isClosed); + int32 i; + float x0, y0; + REPORT(kDebug, fPage, "StrokePolygon numPoints=%ld, isClosed=%d\npoints=", + numPoints, isClosed); + + if (numPoints <= 1) + return; - if (numPoints <= 1) return; - x0 = y0 = 0.0; - - SetColor(); - if (!MakesPDF()) return; + + SetColor(); + if (!MakesPDF()) + return; if (IsClipping()) { BShape shape; @@ -2011,7 +1937,7 @@ PDFWriter::StrokePolygon(int32 numPoints, BPoint *points, bool isClosed) for (i = 1, points ++; i < numPoints; i++, points++) { shape.LineTo(*points); } - if (isClosed) + if (isClosed) shape.Close(); StrokeShape(&shape); } else { @@ -2026,7 +1952,7 @@ PDFWriter::StrokePolygon(int32 numPoints, BPoint *points, bool isClosed) PDF_moveto(fPdf, x0, y0); } } - if (isClosed) + if (isClosed) PDF_lineto(fPdf, x0, y0); StrokeOrClip(); EndTransparency(); @@ -2034,20 +1960,18 @@ PDFWriter::StrokePolygon(int32 numPoints, BPoint *points, bool isClosed) } -// -------------------------------------------------- -void +void PDFWriter::FillPolygon(int32 numPoints, BPoint *points, bool isClosed) { - int32 i; - - REPORT(kDebug, fPage, "FillPolygon numPoints=%ld, isClosed=%dpoints=", \ - numPoints, isClosed); - - SetColor(); - if (!MakesPDF()) return; + REPORT(kDebug, fPage, "FillPolygon numPoints=%ld, isClosed=%dpoints=", + numPoints, isClosed); + + SetColor(); + if (!MakesPDF()) + return; BeginTransparency(); - for ( i = 0; i < numPoints; i++, points++ ) { + for (int32 i = 0; i < numPoints; i++, points++ ) { REPORT(kDebug, fPage, " [%f, %f]", points->x, points->y); if (i != 0) { PDF_lineto(fPdf, tx(points->x), ty(points->y)); @@ -2061,19 +1985,20 @@ PDFWriter::FillPolygon(int32 numPoints, BPoint *points, bool isClosed) } -// -------------------------------------------------- -void PDFWriter::PaintShape(BShape *shape, bool stroke) +void +PDFWriter::PaintShape(BShape *shape, bool stroke) { if (stroke) StrokeShape(shape); else FillShape(shape); } -// -------------------------------------------------- -void PDFWriter::StrokeShape(BShape *shape) +void +PDFWriter::StrokeShape(BShape *shape) { REPORT(kDebug, fPage, "StrokeShape"); - SetColor(); - if (!MakesPDF()) return; + SetColor(); + if (!MakesPDF()) + return; BeginTransparency(); DrawShape iterator(this, true); iterator.Iterate(shape); @@ -2081,11 +2006,11 @@ void PDFWriter::StrokeShape(BShape *shape) } -// -------------------------------------------------- -void PDFWriter::FillShape(BShape *shape) +void +PDFWriter::FillShape(BShape *shape) { REPORT(kDebug, fPage, "FillShape"); - SetColor(); + SetColor(); if (!MakesPDF()) return; BeginTransparency(); DrawShape iterator(this, false); @@ -2094,20 +2019,23 @@ void PDFWriter::FillShape(BShape *shape) } -// -------------------------------------------------- void -PDFWriter::ClipToPicture(BPicture *picture, BPoint point, bool clip_to_inverse_picture) +PDFWriter::ClipToPicture(BPicture *picture, BPoint point, + bool clipToInversePicture) { - REPORT(kDebug, fPage, "ClipToPicture at (%f, %f) clip_to_inverse_picture = %s", point.x, point.y, clip_to_inverse_picture ? "true" : "false"); - if (!MakesPDF()) return; - if (clip_to_inverse_picture) { + REPORT(kDebug, fPage, "ClipToPicture at (%f, %f) clip_to_inverse_picture " + "= %s", point.x, point.y, clipToInversePicture ? "true" : "false"); + + if (!MakesPDF()) + return; + if (clipToInversePicture) { REPORT(kError, fPage, "Clipping to inverse picture not implemented!"); return; } if (fMode == kDrawingMode) { const bool set_origin = point.x != 0 || point.y != 0; - PushInternalState(); - if (set_origin) { + PushInternalState(); + if (set_origin) { SetOrigin(point); PushInternalState(); } @@ -2117,40 +2045,41 @@ PDFWriter::ClipToPicture(BPicture *picture, BPoint point, bool clip_to_inverse_p fMode = kDrawingMode; // and clip to it/them PDF_clip(fPdf); - + if (set_origin) { PopInternalState(); } - PopInternalState(); - + PopInternalState(); + REPORT(kDebug, fPage, "Returning from ClipToPicture"); } else { - REPORT(kError, fPage, "Nested call of ClipToPicture not implemented yet!"); + REPORT(kError, fPage, + "Nested call of ClipToPicture not implemented yet!"); } } -// -------------------------------------------------- -void -PDFWriter::DrawPixels(BRect src, BRect dest, int32 width, int32 height, int32 bytesPerRow, int32 pixelFormat, - int32 flags, void *data) + +void +PDFWriter::DrawPixels(BRect src, BRect dest, int32 width, int32 height, + int32 bytesPerRow, int32 pixelFormat, int32 flags, void *data) { - REPORT(kDebug, fPage, "DrawPixels src=[%f, %f, %f, %f], dest=[%f, %f, %f, %f], " \ - "width=%ld, height=%ld, bytesPerRow=%ld, pixelFormat=%ld, " \ - "flags=%ld, data=%p", \ - src.left, src.top, src.right, src.bottom, \ - dest.left, dest.top, dest.right, dest.bottom, \ - width, height, bytesPerRow, pixelFormat, flags, data); + REPORT(kDebug, fPage, "DrawPixels src=[%f, %f, %f, %f], dest=[%f, %f, %f, " + "%f], width=%ld, height=%ld, bytesPerRow=%ld, pixelFormat=%ld, " + "flags=%ld, data=%p", src.left, src.top, src.right, src.bottom, + dest.left, dest.top, dest.right, dest.bottom, width, height, bytesPerRow, + pixelFormat, flags, data); SetColor(); - + if (IsClipping()) { REPORT(kError, fPage, "DrawPixels for clipping not implemented yet!"); return; } int maskId, image; - - if (!GetImages(src, width, height, bytesPerRow, pixelFormat, flags, data, &maskId, &image)) { + + if (!GetImages(src, width, height, bytesPerRow, pixelFormat, flags, data, + &maskId, &image)) { return; } if (!MakesPDF()) return; @@ -2159,8 +2088,8 @@ PDFWriter::DrawPixels(BRect src, BRect dest, int32 width, int32 height, int32 by const float scaleY = (dest.Height()+1) / (src.Height()+1); const bool needs_scaling = scaleX != 1.0 || scaleY != 1.0; - - if (needs_scaling) { + + if (needs_scaling) { PDF_save(fPdf); PDF_scale(fPdf, scaleX, scaleY); } @@ -2169,7 +2098,7 @@ PDFWriter::DrawPixels(BRect src, BRect dest, int32 width, int32 height, int32 by // Can use Begin/EndTransparency if the alpha value for each pixel // is the same. // Otherwise we need "SoftMasks". Don't know if PDFlib 5.x already - // supports them. + // supports them. BeginTransparency(); float x = tx(dest.left) / scaleX; @@ -2183,32 +2112,30 @@ PDFWriter::DrawPixels(BRect src, BRect dest, int32 width, int32 height, int32 by } else { REPORT(kError, fPage, "PDF_open_image_file failed!"); } - + #if !USE_IMAGE_CACHE if (maskId != -1) PDF_close_image(fPdf, maskId); -#endif +#endif EndTransparency(); - + if (needs_scaling) PDF_restore(fPdf); } - -// -------------------------------------------------- -void +void PDFWriter::SetClippingRects(BRect *rects, uint32 numRects) { uint32 i; - + REPORT(kDebug, fPage, "SetClippingRects numRects=%ld\nrects=", \ numRects); if (!MakesPDF()) return; - + for ( i = 0; i < numRects; i++, rects++ ) { REPORT(kDebug, fPage, " [%f, %f, %f, %f]", \ rects->left, rects->top, rects->right, rects->bottom); - PDF_moveto(fPdf, tx(rects->left), ty(rects->top)); + PDF_moveto(fPdf, tx(rects->left), ty(rects->top)); PDF_lineto(fPdf, tx(rects->right), ty(rects->top)); PDF_lineto(fPdf, tx(rects->right), ty(rects->bottom)); PDF_lineto(fPdf, tx(rects->left), ty(rects->bottom)); @@ -2218,7 +2145,6 @@ PDFWriter::SetClippingRects(BRect *rects, uint32 numRects) } -// -------------------------------------------------- void PDFWriter::PushState() { @@ -2230,7 +2156,6 @@ PDFWriter::PushState() } -// -------------------------------------------------- void PDFWriter::PopState() { @@ -2242,7 +2167,6 @@ PDFWriter::PopState() } -// -------------------------------------------------- void PDFWriter::EnterStateChange() { @@ -2251,7 +2175,6 @@ PDFWriter::EnterStateChange() } -// -------------------------------------------------- void PDFWriter::ExitStateChange() { @@ -2260,7 +2183,6 @@ PDFWriter::ExitStateChange() } -// -------------------------------------------------- void PDFWriter::EnterFontState() { @@ -2269,7 +2191,6 @@ PDFWriter::EnterFontState() } -// -------------------------------------------------- void PDFWriter::ExitFontState() { @@ -2278,15 +2199,13 @@ PDFWriter::ExitFontState() } -// -------------------------------------------------- void PDFWriter::SetOrigin(BPoint pt) { - REPORT(kDebug, fPage, "SetOrigin pt=[%f, %f]", \ - pt.x, pt.y); + REPORT(kDebug, fPage, "SetOrigin pt=[%f, %f]", pt.x, pt.y); // XXX scale pt with current scaling factor or with - // scaling factor of previous state? (fState->prev->scale) + // scaling factor of previous state? (fState->prev->scale) BPoint o = fState->prev->pdfSystem.Origin(); pdfSystem()->SetOrigin( o.x + pdfSystem()->scale(pt.x), @@ -2295,20 +2214,16 @@ PDFWriter::SetOrigin(BPoint pt) } -// -------------------------------------------------- -void +void PDFWriter::SetPenLocation(BPoint pt) { - REPORT(kDebug, fPage, "SetPenLocation pt=[%f, %f]", \ - pt.x, pt.y); - + REPORT(kDebug, fPage, "SetPenLocation pt=[%f, %f]", pt.x, pt.y); + fState->penX = pt.x; fState->penY = pt.y; } - -// -------------------------------------------------- void PDFWriter::SetDrawingMode(drawing_mode mode) { @@ -2317,8 +2232,6 @@ PDFWriter::SetDrawingMode(drawing_mode mode) } - -// -------------------------------------------------- void PDFWriter::SetLineMode(cap_mode capMode, join_mode joinMode, float miterLimit) { @@ -2334,76 +2247,72 @@ PDFWriter::SetLineMode(cap_mode capMode, join_mode joinMode, float miterLimit) case B_SQUARE_CAP: m = 2; break; } PDF_setlinecap(fPdf, m); - + m = 0; switch (joinMode) { case B_MITER_JOIN: m = 0; break; case B_ROUND_JOIN: m = 1; break; - case B_BUTT_JOIN: // fall through XXX: check this; no equivalent in PDF? - case B_SQUARE_JOIN: // fall through XXX: check this too + case B_BUTT_JOIN: // fall through TODO: check this; no equivalent in PDF? + case B_SQUARE_JOIN: // fall through TODO: check this too case B_BEVEL_JOIN: m = 2; break; } PDF_setlinejoin(fPdf, m); PDF_setmiterlimit(fPdf, miterLimit); - + } -// -------------------------------------------------- void PDFWriter::SetPenSize(float size) { REPORT(kDebug, fPage, "SetPenSize size=%f", size); - if (size <= 0.00001) size = 1; - // XXX scaling required? + if (size <= 0.00001) + size = 1; + + // TODO: scaling required? fState->penSize = scale(size); - if (!MakesPDF()) return; + if (!MakesPDF()) + return; + PDF_setlinewidth(fPdf, size); } -// -------------------------------------------------- void PDFWriter::SetForeColor(rgb_color color) { //if (IsClipping()) return; // ignore - - float red, green, blue; - - red = color.red / 255.0; - green = color.green / 255.0; - blue = color.blue / 255.0; - REPORT(kDebug, fPage, "SetForColor color=[%d, %d, %d, %d] -> [%f, %f, %f]", \ - color.red, color.green, color.blue, color.alpha, \ - red, green, blue); - + float red = color.red / 255.0; + float green = color.green / 255.0; + float blue = color.blue / 255.0; + + REPORT(kDebug, fPage, "SetForColor color=[%d, %d, %d, %d] -> [%f, %f, %f]", + color.red, color.green, color.blue, color.alpha, red, green, blue); + fState->foregroundColor = color; } -// -------------------------------------------------- void PDFWriter::SetBackColor(rgb_color color) { //if (IsClipping()) return; // ignore float red, green, blue; - + red = color.red / 255.0; green = color.green / 255.0; blue = color.blue / 255.0; - REPORT(kDebug, fPage, "SetBackColor color=[%d, %d, %d, %d] -> [%f, %f, %f]", \ - color.red, color.green, color.blue, color.alpha, \ - red, green, blue); - + REPORT(kDebug, fPage, "SetBackColor color=[%d, %d, %d, %d] -> [%f, %f, %f]", + color.red, color.green, color.blue, color.alpha, red, green, blue); + fState->backgroundColor = color; } -// -------------------------------------------------- void PDFWriter::SetStipplePattern(pattern pat) { @@ -2412,7 +2321,6 @@ PDFWriter::SetStipplePattern(pattern pat) } -// -------------------------------------------------- void PDFWriter::SetScale(float scale) { @@ -2421,17 +2329,15 @@ PDFWriter::SetScale(float scale) } -// -------------------------------------------------- void PDFWriter::SetFontFamily(char *family) { REPORT(kDebug, fPage, "SetFontFamily family=\"%s\"", family); - + fState->beFont.SetFamilyAndStyle(family, NULL); } -// -------------------------------------------------- void PDFWriter::SetFontStyle(char *style) { @@ -2441,7 +2347,6 @@ PDFWriter::SetFontStyle(char *style) } -// -------------------------------------------------- void PDFWriter::SetFontSpacing(int32 spacing) { @@ -2452,17 +2357,15 @@ PDFWriter::SetFontSpacing(int32 spacing) } -// -------------------------------------------------- void PDFWriter::SetFontSize(float size) { REPORT(kDebug, fPage, "SetFontSize size=%f", size); - + fState->beFont.SetSize(size); } -// -------------------------------------------------- void PDFWriter::SetFontRotate(float rotation) { @@ -2471,7 +2374,6 @@ PDFWriter::SetFontRotate(float rotation) } -// -------------------------------------------------- void PDFWriter::SetFontEncoding(int32 encoding) { @@ -2480,7 +2382,6 @@ PDFWriter::SetFontEncoding(int32 encoding) } -// -------------------------------------------------- void PDFWriter::SetFontFlags(int32 flags) { @@ -2489,7 +2390,6 @@ PDFWriter::SetFontFlags(int32 flags) } -// -------------------------------------------------- void PDFWriter::SetFontShear(float shear) { @@ -2498,7 +2398,6 @@ PDFWriter::SetFontShear(float shear) } -// -------------------------------------------------- void PDFWriter::SetFontFace(int32 flags) { @@ -2506,23 +2405,20 @@ PDFWriter::SetFontFace(int32 flags) // fState->beFont.SetFace(flags); } -#ifdef CODEWARRIOR - #pragma mark [Redirectors to instance callbacks/handlers] -#endif + +// #pragma mark Redirectors to instance callbacks/handlers -// -------------------------------------------------- -size_t +size_t _WriteData(PDF *pdf, void *data, size_t size) -{ - return ((PDFWriter *) PDF_get_opaque(pdf))->WriteData(data, size); +{ + return ((PDFWriter *)PDF_get_opaque(pdf))->WriteData(data, size); } -// -------------------------------------------------- void _ErrorHandler(PDF *pdf, int type, const char *msg) { - return ((PDFWriter *) PDF_get_opaque(pdf))->ErrorHandler(type, msg); + return ((PDFWriter *)PDF_get_opaque(pdf))->ErrorHandler(type, msg); } diff --git a/src/add-ons/print/drivers/pdf/source/PDFWriter.h b/src/add-ons/print/drivers/pdf/source/PDFWriter.h index 0b129b27d6..a42c895e39 100644 --- a/src/add-ons/print/drivers/pdf/source/PDFWriter.h +++ b/src/add-ons/print/drivers/pdf/source/PDFWriter.h @@ -1,34 +1,12 @@ /* - -PDF Writer printer driver. - -Copyright (c) 2001 OpenBeOS. - -Authors: - Philippe Houdoin - Simon Gauvin - Michael Pfeiffer - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - -*/ - + * Copyright 2001-2009, Haiku, Inc. All Rights Reserved. + * Distributed under the terms of the MIT License. + * + * Authors: + * Philippe Houdoin + * Simon Gauvin + * Michael Pfeiffer + */ #ifndef PDFWRITER_H #define PDFWRITER_H @@ -37,7 +15,7 @@ THE SOFTWARE. #include #include -#include "math.h" +#include #include "PrinterDriver.h" #include "PictureIterator.h" @@ -52,8 +30,8 @@ THE SOFTWARE. #define USE_IMAGE_CACHE 1 -#define RAD2DEGREE(r) (180.0 * r / PI) -#define DEGREE2RAD(d) (PI * d / 180.0) +#define RAD2DEGREE(r) (180.0 * r / M_PI) +#define DEGREE2RAD(d) (M_PI * d / 180.0) class DrawShape; class WebLink; @@ -61,9 +39,7 @@ class Bookmark; class XRefDefs; class XRefDests; -class PDFWriter : public PrinterDriver, public PictureIterator -{ - +class PDFWriter : public PrinterDriver, public PictureIterator { friend class DrawShape; friend class PDFLinePathBuilder; friend class WebLink; @@ -71,12 +47,12 @@ class PDFWriter : public PrinterDriver, public PictureIterator friend class Bookmark; friend class LocalLink; friend class TextLine; - + public: // constructors / destructor PDFWriter(); ~PDFWriter(); - + // public methods status_t BeginJob(); status_t PrintPage(int32 pageNumber, int32 pageCount); @@ -89,11 +65,11 @@ class PDFWriter : public PrinterDriver, public PictureIterator bool LoadBookmarkDefinitions(const char* name); bool LoadXRefsDefinitions(const char* name); void RecordDests(const char* s); - + // PDFLib callbacks size_t WriteData(void *data, size_t size); void ErrorHandler(int type, const char *msg); - + // Image support int32 BytesPerPixel(int32 pixelFormat); @@ -198,19 +174,19 @@ class PDFWriter : public PrinterDriver, public PictureIterator void SetFontFlags(int32 flags); void SetFontShear(float shear); void SetFontFace(int32 flags); - + static inline bool IsSame(const pattern &p1, const pattern &p2); static inline bool IsSame(const rgb_color &c1, const rgb_color &c2); - + private: - + enum PDFVersion { kPDF13, kPDF14, kPDF15 }; - - class State + + class State { public: State *prev; @@ -229,9 +205,9 @@ class PDFWriter : public PrinterDriver, public PictureIterator float penSize; pattern pattern0; int32 fontSpacing; - + // initialize with defalt values - State(float h = a4_height, float x = 0, float y = 0) + State(float h = a4_height, float x = 0, float y = 0) { static rgb_color white = {255, 255, 255, 255}; static rgb_color black = {0, 0, 0, 255}; @@ -241,26 +217,26 @@ class PDFWriter : public PrinterDriver, public PictureIterator pdfSystem.SetOrigin(x, y); penX = 0; penY = 0; - drawingMode = B_OP_COPY; + drawingMode = B_OP_COPY; foregroundColor = white; backgroundColor = black; currentColor = black; - capMode = B_BUTT_CAP; - joinMode = B_MITER_JOIN; - miterLimit = B_DEFAULT_MITER_LIMIT; - penSize = 1; - pattern0 = B_SOLID_HIGH; - fontSpacing = B_STRING_SPACING; + capMode = B_BUTT_CAP; + joinMode = B_MITER_JOIN; + miterLimit = B_DEFAULT_MITER_LIMIT; + penSize = 1; + pattern0 = B_SOLID_HIGH; + fontSpacing = B_STRING_SPACING; } - State(State *prev) + State(State *prev) { *this = *prev; this->prev = prev; } }; - class Font + class Font { public: Font(char *n, int f, font_encoding e) : name(n), font(f), encoding(e) { } @@ -275,14 +251,14 @@ class PDFWriter : public PrinterDriver, public PictureIterator pattern pat; rgb_color lowColor, highColor; int patternId; - + Pattern(const pattern &p, rgb_color low, rgb_color high, int id) : pat(p) , lowColor(low) , highColor(high) , patternId(id) {}; - + inline bool Matches(const pattern &p, rgb_color low, rgb_color high) const { return IsSame(pat, p) && IsSame(lowColor, low) && IsSame(highColor, high); }; @@ -292,19 +268,19 @@ class PDFWriter : public PrinterDriver, public PictureIterator { uint8 alpha; int handle; - public: + public: Transparency(uint8 alpha, int handle) : alpha(alpha) , handle(handle) {}; - + inline bool Matches(uint8 alpha) const { return this->alpha == alpha; }; - + inline int Handle() const { return handle; } }; - + PDFVersion fPDFVersion; FILE *fLog; PDF *fPdf; @@ -329,8 +305,8 @@ class PDFWriter : public PrinterDriver, public PictureIterator TextLine fTextLine; TList fUsedFonts; UserDefinedEncodings fUserDefinedEncodings; - - enum + + enum { kDrawingMode, kClippingMode @@ -362,7 +338,7 @@ class PDFWriter : public PrinterDriver, public PictureIterator inline cap_mode LineCapMode() const { return fState->capMode; } inline join_mode LineJoinMode() const { return fState->joinMode; } inline float LineMiterLimit() const { return fState->miterLimit; } - + bool StoreTranslatorBitmap(BBitmap *bitmap, const char *filename, uint32 type); void GetFontName(BFont *font, char *fontname); @@ -383,7 +359,7 @@ class PDFWriter : public PrinterDriver, public PictureIterator void CreatePattern(); int FindPattern(); void SetPattern(); - + void StrokeOrClip(); void FillOrClip(); void Paint(bool stroke); @@ -394,9 +370,7 @@ class PDFWriter : public PrinterDriver, public PictureIterator }; - -// -------------------------------------------------- -inline bool +inline bool PDFWriter::IsSame(const pattern &p1, const pattern &p2) { char *a = (char*)p1.data; @@ -405,8 +379,7 @@ PDFWriter::IsSame(const pattern &p1, const pattern &p2) } -// -------------------------------------------------- -inline bool +inline bool PDFWriter::IsSame(const rgb_color &c1, const rgb_color &c2) { char *a = (char*)&c1; @@ -419,4 +392,4 @@ PDFWriter::IsSame(const rgb_color &c1, const rgb_color &c2) size_t _WriteData(PDF *p, void *data, size_t size); void _ErrorHandler(PDF *p, int type, const char *msg); -#endif // #if PDFWRITER_H +#endif // PDFWRITER_H diff --git a/src/apps/cortex/addons/Flanger/FlangerNode.cpp b/src/apps/cortex/addons/Flanger/FlangerNode.cpp index b0739da50a..ec7b982786 100644 --- a/src/apps/cortex/addons/Flanger/FlangerNode.cpp +++ b/src/apps/cortex/addons/Flanger/FlangerNode.cpp @@ -25,7 +25,7 @@ float calc_sweep_delta( const media_raw_audio_format& format, float fRate); - + float calc_sweep_base( const media_raw_audio_format& format, float fDelay, float fDepth); @@ -35,34 +35,34 @@ float calc_sweep_factor( float fDepth); // -------------------------------------------------------- // -// constants +// constants // -------------------------------------------------------- // // input-ID symbols enum input_id_t { ID_AUDIO_INPUT }; - + // output-ID symbols enum output_id_t { ID_AUDIO_MIX_OUTPUT //ID_AUDIO_WET_OUTPUT ... }; - + // parameter ID enum param_id_t { P_MIX_RATIO_LABEL = 100, P_MIX_RATIO, - + P_SWEEP_RATE_LABEL = 200, P_SWEEP_RATE, - + P_DELAY_LABEL = 300, P_DELAY, - + P_DEPTH_LABEL = 400, P_DEPTH, - + P_FEEDBACK_LABEL = 500, P_FEEDBACK }; @@ -70,7 +70,7 @@ enum param_id_t { const float FlangerNode::s_fMaxDelay = 100.0; const char* const FlangerNode::s_nodeName = "FlangerNode"; - + // -------------------------------------------------------- // // ctor/dtor // -------------------------------------------------------- // @@ -78,7 +78,7 @@ const char* const FlangerNode::s_nodeName = "FlangerNode"; FlangerNode::~FlangerNode() { // shut down Quit(); - + // free delay buffer if(m_pDelayBuffer) delete m_pDelayBuffer; @@ -91,27 +91,27 @@ FlangerNode::FlangerNode(BMediaAddOn* pAddOn) : BBufferProducer(B_MEDIA_RAW_AUDIO), BControllable(), BMediaEventLooper(), - + // * init connection state m_outputEnabled(true), m_downstreamLatency(0), m_processingLatency(0), - + // * init filter state m_pDelayBuffer(0), - + // * init add-on stuff m_pAddOn(pAddOn) { - + // PRINT(( // "\n" // "--*-- FlangerNode() [%s] --*--\n\n", // __BUILD_DATE)); -// +// // the rest of the initialization happens in NodeRegistered(). } - - + + // -------------------------------------------------------- // // *** BMediaNode // -------------------------------------------------------- // @@ -128,7 +128,7 @@ status_t FlangerNode::HandleMessage( BControllable::HandleMessage(code, pData, size) && BMediaNode::HandleMessage(code, pData, size)) BMediaNode::HandleBadMessage(code, pData, size); - + // +++++ return error on bad message? return B_OK; } @@ -148,13 +148,13 @@ void FlangerNode::SetRunMode( // +++++ if(mode == B_OFFLINE) ReportError(B_NODE_FAILED_SET_RUN_MODE); - + // +++++ any other work to do? - + // hand off BMediaEventLooper::SetRunMode(mode); } - + // -------------------------------------------------------- // // *** BMediaEventLooper // -------------------------------------------------------- // @@ -165,20 +165,20 @@ void FlangerNode::HandleEvent( bool realTimeEvent) { ASSERT(pEvent); - + switch(pEvent->type) { case BTimedEventQueue::B_PARAMETER: handleParameterEvent(pEvent); break; - + case BTimedEventQueue::B_START: handleStartEvent(pEvent); break; - + case BTimedEventQueue::B_STOP: handleStopEvent(pEvent); break; - + default: ignoreEvent(pEvent); break; @@ -189,7 +189,7 @@ void FlangerNode::HandleEvent( // been registered. This is derived from BMediaNode; BMediaEventLooper // implements it to call Run() automatically when the node is registered; // if you implement NodeRegistered() you should call through to -// BMediaEventLooper::NodeRegistered() after you've done your custom +// BMediaEventLooper::NodeRegistered() after you've done your custom // operations." void FlangerNode::NodeRegistered() { @@ -203,11 +203,11 @@ void FlangerNode::NodeRegistered() { // figure preferred ('template') format m_preferredFormat.type = B_MEDIA_RAW_AUDIO; getPreferredFormat(m_preferredFormat); - + // initialize current format m_format.type = B_MEDIA_RAW_AUDIO; m_format.u.raw_audio = media_raw_audio_format::wildcard; - + // init input m_input.destination.port = ControlPort(); m_input.destination.id = ID_AUDIO_INPUT; @@ -215,7 +215,7 @@ void FlangerNode::NodeRegistered() { m_input.source = media_source::null; m_input.format = m_format; strncpy(m_input.name, "Audio Input", B_MEDIA_NAME_LENGTH); - + // init output m_output.source.port = ControlPort(); m_output.source.id = ID_AUDIO_MIX_OUTPUT; @@ -228,7 +228,7 @@ void FlangerNode::NodeRegistered() { initParameterValues(); initParameterWeb(); } - + // "Augment OfflineTime() to compute the node's current time; it's called // by the Media Kit when it's in offline mode. Update any appropriate // internal information as well, then call through to the BMediaEventLooper @@ -265,9 +265,9 @@ status_t FlangerNode::AcceptFormat( *pioFormat); return B_OK; } - + // "If you're writing a node, and receive a buffer with the B_SMALL_BUFFER -// flag set, you must recycle the buffer before returning." +// flag set, you must recycle the buffer before returning." void FlangerNode::BufferReceived( BBuffer* pBuffer) { @@ -281,7 +281,7 @@ void FlangerNode::BufferReceived( pBuffer->Recycle(); return; } - + if(pBuffer->Header()->time_source != TimeSource()->ID()) { PRINT(("* timesource mismatch\n")); } @@ -292,9 +292,9 @@ void FlangerNode::BufferReceived( pBuffer->Recycle(); return; } - + // process and retransmit buffer - filterBuffer(pBuffer); + filterBuffer(pBuffer); status_t err = SendBuffer(pBuffer, m_output.destination); if(err < B_OK) { @@ -304,7 +304,7 @@ void FlangerNode::BufferReceived( } // sent! } - + // * make sure to fill in poInput->format with the contents of // pFormat; as of R4.5 the Media Kit passes poInput->format to // the producer in BBufferProducer::Connect(). @@ -314,10 +314,10 @@ status_t FlangerNode::Connected( const media_destination& destination, const media_format& format, media_input* poInput) { - + PRINT(("FlangerNode::Connected()\n" "\tto source %ld\n", source.id)); - + // sanity check if(destination != m_input.destination) { PRINT(("\tbad destination\n")); @@ -327,22 +327,22 @@ status_t FlangerNode::Connected( PRINT(("\talready connected\n")); return B_MEDIA_ALREADY_CONNECTED; } - + // initialize input m_input.source = source; m_input.format = format; *poInput = m_input; - + // store format (this now constrains the output format) m_format = format; - + return B_OK; } void FlangerNode::Disconnected( const media_source& source, const media_destination& destination) { - + PRINT(("FlangerNode::Disconnected()\n")); // sanity checks @@ -359,26 +359,26 @@ void FlangerNode::Disconnected( // mark disconnected m_input.source = media_source::null; - + // no output? clear format: if(m_output.destination == media_destination::null) { m_format.u.raw_audio = media_raw_audio_format::wildcard; } - + m_input.format = m_format; } - + void FlangerNode::DisposeInputCookie( int32 cookie) {} - + // "You should implement this function so your node will know that the data // format is going to change. Note that this may be called in response to // your AcceptFormat() call, if your AcceptFormat() call alters any wildcard -// fields in the specified format. +// fields in the specified format. // // Because FormatChanged() is called by the producer, you don't need to (and -// shouldn't) ask it if the new format is acceptable. +// shouldn't) ask it if the new format is acceptable. // // If the format change isn't possible, return an appropriate error from // FormatChanged(); this error will be passed back to the producer that @@ -389,37 +389,37 @@ status_t FlangerNode::FormatChanged( const media_destination& destination, int32 changeTag, const media_format& newFormat) { - + // flat-out deny format changes return B_MEDIA_BAD_FORMAT; } - + status_t FlangerNode::GetLatencyFor( const media_destination& destination, bigtime_t* poLatency, media_node_id* poTimeSource) { - + PRINT(("FlangerNode::GetLatencyFor()\n")); - + // sanity check if(destination != m_input.destination) { PRINT(("\tbad destination\n")); return B_MEDIA_BAD_DESTINATION; } - + *poLatency = m_downstreamLatency + m_processingLatency; PRINT(("\treturning %Ld\n", *poLatency)); *poTimeSource = TimeSource()->ID(); return B_OK; } - + status_t FlangerNode::GetNextInput( int32* pioCookie, media_input* poInput) { if(*pioCookie) return B_BAD_INDEX; - + ++*pioCookie; *poInput = m_input; return B_OK; @@ -431,16 +431,16 @@ void FlangerNode::ProducerDataStatus( bigtime_t tpWhen) { PRINT(("FlangerNode::ProducerDataStatus()\n")); - + // sanity check if(destination != m_input.destination) { PRINT(("\tbad destination\n")); } - + if(m_output.destination != media_destination::null) { // pass status downstream status_t err = SendDataStatus( - status, + status, m_output.destination, tpWhen); if(err < B_OK) { @@ -448,7 +448,7 @@ void FlangerNode::ProducerDataStatus( } } } - + // "This function is provided to aid in supporting media formats in which the // outer encapsulation layer doesn't supply timing information. Producers will // tag the buffers they generate with seek tags; these tags can be used to @@ -466,7 +466,7 @@ status_t FlangerNode::SeekTagRequested( "\tNot implemented.\n")); return B_ERROR; } - + // -------------------------------------------------------- // // *** BBufferProducer // -------------------------------------------------------- // @@ -476,7 +476,7 @@ status_t FlangerNode::SeekTagRequested( // immediately send the next buffer to the consumer. The previousBufferID, // previousTime, and previousTag arguments identify the last buffer the // consumer received. Your node should respond by sending the next buffer -// after the one described. +// after the one described. // // The previousTag may be NULL. // Return B_OK if all is well; otherwise return an appropriate error code." @@ -486,34 +486,34 @@ void FlangerNode::AdditionalBufferRequested( media_buffer_id previousBufferID, bigtime_t previousTime, const media_seek_tag* pPreviousTag) { - + PRINT(("FlangerNode::AdditionalBufferRequested\n" "\tOffline mode not implemented.")); } - + void FlangerNode::Connect( status_t status, const media_source& source, const media_destination& destination, const media_format& format, char* pioName) { - + PRINT(("FlangerNode::Connect()\n")); status_t err; - - // connection failed? + + // connection failed? if(status < B_OK) { PRINT(("\tStatus: %s\n", strerror(status))); // 'unreserve' the output m_output.destination = media_destination::null; return; } - + // connection established: strncpy(pioName, m_output.name, B_MEDIA_NAME_LENGTH); m_output.destination = destination; m_format = format; - + // figure downstream latency media_node_id timeSource; err = FindLatencyFor(m_output.destination, &m_downstreamLatency, &timeSource); @@ -521,17 +521,17 @@ void FlangerNode::Connect( PRINT(("\t!!! FindLatencyFor(): %s\n", strerror(err))); } PRINT(("\tdownstream latency = %Ld\n", m_downstreamLatency)); - + // prepare the filter initFilter(); // figure processing time m_processingLatency = calcProcessingLatency(); PRINT(("\tprocessing latency = %Ld\n", m_processingLatency)); - + // store summed latency SetEventLatency(m_downstreamLatency + m_processingLatency); - + if(m_input.source != media_source::null) { // pass new latency upstream err = SendLatencyChange( @@ -547,14 +547,14 @@ void FlangerNode::Connect( buffer_duration( m_format.u.raw_audio)); } - + void FlangerNode::Disconnect( const media_source& source, const media_destination& destination) { PRINT(("FlangerNode::Disconnect()\n")); - - // sanity checks + + // sanity checks if(source != m_output.source) { PRINT(("\tbad source\n")); return; @@ -563,25 +563,25 @@ void FlangerNode::Disconnect( PRINT(("\tbad destination\n")); return; } - + // clean up m_output.destination = media_destination::null; - + // no input? clear format: if(m_input.source == media_source::null) { m_format.u.raw_audio = media_raw_audio_format::wildcard; } - + m_output.format = m_format; - + // +++++ other cleanup goes here } - + status_t FlangerNode::DisposeOutputCookie( int32 cookie) { return B_OK; } - + void FlangerNode::EnableOutput( const media_source& source, bool enabled, @@ -591,39 +591,39 @@ void FlangerNode::EnableOutput( PRINT(("\tbad source\n")); return; } - + m_outputEnabled = enabled; } - + status_t FlangerNode::FormatChangeRequested( const media_source& source, const media_destination& destination, media_format* pioFormat, int32* _deprecated_) { - + // deny PRINT(("FlangerNode::FormatChangeRequested()\n" "\tNot supported.\n")); - + return B_MEDIA_BAD_FORMAT; } - + status_t FlangerNode::FormatProposal( const media_source& source, media_format* pioFormat) { PRINT(("FlangerNode::FormatProposal()\n")); - + if(source != m_output.source) { PRINT(("\tbad source\n")); return B_MEDIA_BAD_SOURCE; } - + if(pioFormat->type != B_MEDIA_RAW_AUDIO) { PRINT(("\tbad type\n")); return B_MEDIA_BAD_FORMAT; } - + validateProposedFormat( (m_format.u.raw_audio.format != media_raw_audio_format::wildcard.format) ? m_format : @@ -631,45 +631,45 @@ status_t FlangerNode::FormatProposal( *pioFormat); return B_OK; } - + status_t FlangerNode::FormatSuggestionRequested( media_type type, int32 quality, media_format* poFormat) { - + PRINT(("FlangerNode::FormatSuggestionRequested()\n")); if(type != B_MEDIA_RAW_AUDIO) { PRINT(("\tbad type\n")); return B_MEDIA_BAD_FORMAT; } - + if(m_format.u.raw_audio.format != media_raw_audio_format::wildcard.format) *poFormat = m_format; else *poFormat = m_preferredFormat; return B_OK; } - + status_t FlangerNode::GetLatency( bigtime_t* poLatency) { - + PRINT(("FlangerNode::GetLatency()\n")); *poLatency = EventLatency() + SchedulingLatency(); PRINT(("\treturning %Ld\n", *poLatency)); - + return B_OK; } - + status_t FlangerNode::GetNextOutput( int32* pioCookie, media_output* poOutput) { if(*pioCookie) return B_BAD_INDEX; - + ++*pioCookie; *poOutput = m_output; - + return B_OK; } @@ -687,7 +687,7 @@ void FlangerNode::LatencyChanged( uint32 flags) { PRINT(("FlangerNode::LatencyChanged()\n")); - + if(source != m_output.source) { PRINT(("\tBad source.\n")); return; @@ -696,10 +696,10 @@ void FlangerNode::LatencyChanged( PRINT(("\tBad destination.\n")); return; } - + m_downstreamLatency = newLatency; SetEventLatency(m_downstreamLatency + m_processingLatency); - + if(m_input.source != media_source::null) { // pass new latency upstream status_t err = SendLatencyChange( @@ -719,7 +719,7 @@ void FlangerNode::LateNoticeReceived( PRINT(("FlangerNode::LateNoticeReceived()\n" "\thowLate == %Ld\n" "\twhen == %Ld\n", howLate, tpWhen)); - + if(source != m_output.source) { PRINT(("\tBad source.\n")); return; @@ -729,9 +729,9 @@ void FlangerNode::LateNoticeReceived( PRINT(("\t!!! No input to blame.\n")); return; } - + // +++++ check run mode? - + // pass the buck, since this node doesn't schedule buffer // production NotifyLateProducer( @@ -739,7 +739,7 @@ void FlangerNode::LateNoticeReceived( howLate, tpWhen); } - + // PrepareToConnect() is the second stage of format negotiations that happens // inside BMediaRoster::Connect(). At this point, the consumer's AcceptFormat() // method has been called, and that node has potentially changed the proposed @@ -757,7 +757,7 @@ status_t FlangerNode::PrepareToConnect( string_for_format(*pioFormat, formatStr, 255); PRINT(("FlangerNode::PrepareToConnect()\n" "\tproposed format: %s\n", formatStr)); - + if(source != m_output.source) { PRINT(("\tBad source.\n")); return B_MEDIA_BAD_SOURCE; @@ -766,7 +766,7 @@ status_t FlangerNode::PrepareToConnect( PRINT(("\tAlready connected.\n")); return B_MEDIA_ALREADY_CONNECTED; } - + if(pioFormat->type != B_MEDIA_RAW_AUDIO) { PRINT(("\tBad format type.\n")); return B_MEDIA_BAD_FORMAT; @@ -783,21 +783,21 @@ status_t FlangerNode::PrepareToConnect( // no go return err; } - + // fill in wildcards specializeOutputFormat(*pioFormat); - + // reserve the output m_output.destination = destination; m_output.format = *pioFormat; - + // pass back source & output name *poSource = m_output.source; strncpy(poName, m_output.name, B_MEDIA_NAME_LENGTH); - + return B_OK; } - + status_t FlangerNode::SetBufferGroup( const media_source& source, BBufferGroup* pGroup) { @@ -807,12 +807,12 @@ status_t FlangerNode::SetBufferGroup( PRINT(("\tBad source.\n")); return B_MEDIA_BAD_SOURCE; } - + if(m_input.source == media_source::null) { PRINT(("\tNo producer to send buffers to.\n")); return B_ERROR; } - + // +++++ is this right? buffer-group selection gets // all asynchronous and weird... int32 changeTag; @@ -822,14 +822,14 @@ status_t FlangerNode::SetBufferGroup( pGroup, 0, &changeTag); } - + status_t FlangerNode::SetPlayRate( int32 numerator, int32 denominator) { // not supported return B_ERROR; } - + status_t FlangerNode::VideoClippingChanged( const media_source& source, int16 numShorts, @@ -849,7 +849,7 @@ status_t FlangerNode::GetParameterValue( bigtime_t* poLastChangeTime, void* poValue, size_t* pioSize) { - + // PRINT(("FlangerNode::GetParameterValue()\n")); // all parameters are floats @@ -863,7 +863,7 @@ status_t FlangerNode::GetParameterValue( *(float*)poValue = m_fMixRatio; *poLastChangeTime = m_tpMixRatioChanged; break; - + case P_SWEEP_RATE: *(float*)poValue = m_fSweepRate; *poLastChangeTime = m_tpSweepRateChanged; @@ -873,30 +873,30 @@ status_t FlangerNode::GetParameterValue( *(float*)poValue = m_fDelay; *poLastChangeTime = m_tpDelayChanged; break; - + case P_DEPTH: *(float*)poValue = m_fDepth; *poLastChangeTime = m_tpDepthChanged; break; - + case P_FEEDBACK: *(float*)poValue = m_fFeedback; *poLastChangeTime = m_tpFeedbackChanged; break; - + default: return B_ERROR; } return B_OK; } - + void FlangerNode::SetParameterValue( int32 id, bigtime_t changeTime, const void* pValue, size_t size) { - + switch(id) { case P_MIX_RATIO: case P_SWEEP_RATE: @@ -921,7 +921,7 @@ void FlangerNode::SetParameterValue( EventQueue()->AddEvent(ev); break; } - } + } } // -------------------------------------------------------- // @@ -930,17 +930,17 @@ void FlangerNode::SetParameterValue( void FlangerNode::handleParameterEvent( const media_timed_event* pEvent) { - + float value = *(float*)pEvent->user_data; int32 id = pEvent->bigdata; size_t size = pEvent->data; bigtime_t now = TimeSource()->Now(); - + switch(id) { case P_MIX_RATIO: if(value == m_fMixRatio) break; - + // set m_fMixRatio = value; m_tpMixRatioChanged = now; @@ -955,17 +955,17 @@ void FlangerNode::handleParameterEvent( case P_SWEEP_RATE: if(value == m_fSweepRate) break; - + // set m_fSweepRate = value; m_tpSweepRateChanged = now; - + if(m_output.destination != media_destination::null) { m_fThetaInc = calc_sweep_delta( m_format.u.raw_audio, m_fSweepRate); } - + // broadcast BroadcastNewParameterValue( now, @@ -977,17 +977,17 @@ void FlangerNode::handleParameterEvent( case P_DELAY: if(value == m_fDelay) break; - + // set m_fDelay = value; m_tpDelayChanged = now; - + if(m_output.destination != media_destination::null) { m_fSweepBase = calc_sweep_base( m_format.u.raw_audio, m_fDelay, m_fDepth); } - + // broadcast BroadcastNewParameterValue( now, @@ -999,11 +999,11 @@ void FlangerNode::handleParameterEvent( case P_DEPTH: if(value == m_fDepth) break; - + // set m_fDepth = value; m_tpDepthChanged = now; - + if(m_output.destination != media_destination::null) { m_fSweepBase = calc_sweep_base( m_format.u.raw_audio, @@ -1012,7 +1012,7 @@ void FlangerNode::handleParameterEvent( m_format.u.raw_audio, m_fDepth); } - + // broadcast BroadcastNewParameterValue( now, @@ -1020,7 +1020,7 @@ void FlangerNode::handleParameterEvent( &m_fDepth, size); break; - + case P_FEEDBACK: if(value == m_fFeedback) break; @@ -1037,27 +1037,27 @@ void FlangerNode::handleParameterEvent( break; } } - + void FlangerNode::handleStartEvent( const media_timed_event* pEvent) { PRINT(("FlangerNode::handleStartEvent\n")); - startFilter(); + startFilter(); } - + void FlangerNode::handleStopEvent( const media_timed_event* pEvent) { PRINT(("FlangerNode::handleStopEvent\n")); - + stopFilter(); } - + void FlangerNode::ignoreEvent( const media_timed_event* pEvent) { PRINT(("FlangerNode::ignoreEvent\n")); - + } - + // -------------------------------------------------------- // // *** internal operations @@ -1069,11 +1069,11 @@ void FlangerNode::ignoreEvent( void FlangerNode::getPreferredFormat( media_format& ioFormat) { ASSERT(ioFormat.type == B_MEDIA_RAW_AUDIO); - + ioFormat.u.raw_audio = media_raw_audio_format::wildcard; ioFormat.u.raw_audio.channel_count = 1; ioFormat.u.raw_audio.format = media_raw_audio_format::B_AUDIO_FLOAT; - + // ioFormat.u.raw_audio.frame_rate = 44100.0; // ioFormat.u.raw_audio.buffer_size = 0x1000; } @@ -1088,20 +1088,20 @@ void FlangerNode::getPreferredFormat( status_t FlangerNode::validateProposedFormat( const media_format& preferredFormat, media_format& ioProposedFormat) { - + char formatStr[256]; PRINT(("FlangerNode::validateProposedFormat()\n")); ASSERT(preferredFormat.type == B_MEDIA_RAW_AUDIO); - + string_for_format(preferredFormat, formatStr, 255); PRINT(("\ttemplate format: %s\n", formatStr)); string_for_format(ioProposedFormat, formatStr, 255); PRINT(("\tproposed format: %s\n", formatStr)); - + status_t err = B_OK; - + if(ioProposedFormat.type != B_MEDIA_RAW_AUDIO) { // out of the ballpark ioProposedFormat = preferredFormat; @@ -1114,7 +1114,7 @@ status_t FlangerNode::validateProposedFormat( media_raw_audio_format& f = ioProposedFormat.u.raw_audio; // template format const media_raw_audio_format& pref = preferredFormat.u.raw_audio; - + if(pref.frame_rate != wild.frame_rate) { if(f.frame_rate != pref.frame_rate) { if(f.frame_rate != wild.frame_rate) @@ -1130,7 +1130,7 @@ status_t FlangerNode::validateProposedFormat( f.channel_count = pref.channel_count; } } - + if(pref.format != wild.format) { if(f.format != pref.format) { if(f.format != wild.format) @@ -1138,7 +1138,7 @@ status_t FlangerNode::validateProposedFormat( f.format = pref.format; } } - + if(pref.byte_order != wild.byte_order) { if(f.byte_order != pref.byte_order) { if(f.byte_order != wild.byte_order) @@ -1146,7 +1146,7 @@ status_t FlangerNode::validateProposedFormat( f.byte_order = pref.byte_order; } } - + if(pref.buffer_size != wild.buffer_size) { if(f.buffer_size != pref.buffer_size) { if(f.buffer_size != wild.buffer_size) @@ -1154,32 +1154,32 @@ status_t FlangerNode::validateProposedFormat( f.buffer_size = pref.buffer_size; } } - + if(err != B_OK) { string_for_format(ioProposedFormat, formatStr, 255); PRINT(( "\tformat conflict; suggesting:\n\tformat %s\n", formatStr)); } - - return err; + + return err; } // fill in wildcards in the given format. // (assumes the format passes validateProposedFormat().) void FlangerNode::specializeOutputFormat( media_format& ioFormat) { - + char formatStr[256]; string_for_format(ioFormat, formatStr, 255); PRINT(("FlangerNode::specializeOutputFormat()\n" "\tinput format: %s\n", formatStr)); - + ASSERT(ioFormat.type == B_MEDIA_RAW_AUDIO); - + // carpal_tunnel_paranoia media_raw_audio_format& f = ioFormat.u.raw_audio; media_raw_audio_format& w = media_raw_audio_format::wildcard; - + if(f.frame_rate == w.frame_rate) f.frame_rate = 44100.0; if(f.channel_count == w.channel_count) { @@ -1187,7 +1187,7 @@ void FlangerNode::specializeOutputFormat( if(m_input.source != media_source::null) f.channel_count = m_input.format.u.raw_audio.channel_count; else - f.channel_count = 1; + f.channel_count = 1; } if(f.format == w.format) f.format = media_raw_audio_format::B_AUDIO_FLOAT; @@ -1204,10 +1204,10 @@ void FlangerNode::specializeOutputFormat( void FlangerNode::initParameterValues() { m_fMixRatio = 0.5; m_tpMixRatioChanged = 0LL; - + m_fSweepRate = 0.1; m_tpSweepRateChanged = 0LL; - + m_fDelay = 10.0; m_tpDelayChanged = 0LL; @@ -1217,7 +1217,7 @@ void FlangerNode::initParameterValues() { m_fFeedback = 0.1; m_tpFeedbackChanged = 0LL; } - + // create and register a parameter web void FlangerNode::initParameterWeb() { BParameterWeb* pWeb = new BParameterWeb(); @@ -1226,7 +1226,7 @@ void FlangerNode::initParameterWeb() { BNullParameter* label; BContinuousParameter* value; BParameterGroup* g; - + // mix ratio g = pTopGroup->MakeGroup("Mix Ratio"); label = g->MakeNullParameter( @@ -1234,7 +1234,7 @@ void FlangerNode::initParameterWeb() { B_MEDIA_NO_TYPE, "Mix Ratio", B_GENERIC); - + value = g->MakeContinuousParameter( P_MIX_RATIO, B_MEDIA_NO_TYPE, @@ -1250,7 +1250,7 @@ void FlangerNode::initParameterWeb() { B_MEDIA_NO_TYPE, "Sweep Rate", B_GENERIC); - + value = g->MakeContinuousParameter( P_SWEEP_RATE, B_MEDIA_NO_TYPE, @@ -1266,7 +1266,7 @@ void FlangerNode::initParameterWeb() { B_MEDIA_NO_TYPE, "Delay", B_GENERIC); - + value = g->MakeContinuousParameter( P_DELAY, B_MEDIA_NO_TYPE, @@ -1282,7 +1282,7 @@ void FlangerNode::initParameterWeb() { B_MEDIA_NO_TYPE, "Depth", B_GENERIC); - + value = g->MakeContinuousParameter( P_DEPTH, B_MEDIA_NO_TYPE, @@ -1298,7 +1298,7 @@ void FlangerNode::initParameterWeb() { B_MEDIA_NO_TYPE, "Feedback", B_GENERIC); - + value = g->MakeContinuousParameter( P_FEEDBACK, B_MEDIA_NO_TYPE, @@ -1315,7 +1315,7 @@ void FlangerNode::initParameterWeb() { void FlangerNode::initFilter() { PRINT(("FlangerNode::initFilter()\n")); ASSERT(m_format.u.raw_audio.format != media_raw_audio_format::wildcard.format); - + if(!m_pDelayBuffer) { m_pDelayBuffer = new AudioBuffer( m_format.u.raw_audio, @@ -1324,7 +1324,7 @@ void FlangerNode::initFilter() { (bigtime_t)s_fMaxDelay*1000LL)); m_pDelayBuffer->zero(); } - + m_framesSent = 0; m_delayWriteFrame = 0; m_fTheta = 0.0; @@ -1332,7 +1332,7 @@ void FlangerNode::initFilter() { m_fSweepBase = calc_sweep_base(m_format.u.raw_audio, m_fDelay, m_fDepth); m_fSweepFactor = calc_sweep_factor(m_format.u.raw_audio, m_fDepth); -// +// // PRINT(( // "\tFrames %ld\n" // "\tDelay %.2f\n" @@ -1353,29 +1353,29 @@ void FlangerNode::stopFilter() { // figure processing latency by doing 'dry runs' of filterBuffer() bigtime_t FlangerNode::calcProcessingLatency() { PRINT(("FlangerNode::calcProcessingLatency()\n")); - + if(m_output.destination == media_destination::null) { PRINT(("\tNot connected.\n")); return 0LL; } - + // allocate a temporary buffer group BBufferGroup* pTestGroup = new BBufferGroup( m_output.format.u.raw_audio.buffer_size, 1); - + // fetch a buffer BBuffer* pBuffer = pTestGroup->RequestBuffer( m_output.format.u.raw_audio.buffer_size); ASSERT(pBuffer); - + pBuffer->Header()->type = B_MEDIA_RAW_AUDIO; pBuffer->Header()->size_used = m_output.format.u.raw_audio.buffer_size; - + // run the test bigtime_t preTest = system_time(); filterBuffer(pBuffer); bigtime_t elapsed = system_time()-preTest; - + // clean up pBuffer->Recycle(); delete pTestGroup; @@ -1412,7 +1412,7 @@ void FlangerNode::filterBuffer( // - update readOffset AudioBuffer input(m_format.u.raw_audio, pBuffer); - + ASSERT( m_format.u.raw_audio.channel_count == 1 || m_format.u.raw_audio.channel_count == 2); @@ -1421,7 +1421,7 @@ void FlangerNode::filterBuffer( uint32 samples = input.frames() * channels; for(uint32 inPos = 0; inPos < samples; ++inPos) { - + // read from input buffer _frame inFrame; inFrame.channel[0] = ((float*)input.data())[inPos]; @@ -1433,7 +1433,7 @@ void FlangerNode::filterBuffer( float fReadFrame = (float)m_delayWriteFrame - readOffset; if(fReadFrame < 0.0) fReadFrame += m_pDelayBuffer->frames(); - + // float delayed; @@ -1449,7 +1449,7 @@ void FlangerNode::filterBuffer( if(readFrameLo != (int32)fReadFrame) { // interpolate (A) - uint32 readFrameHi = (int32)ceil(fReadFrame); + uint32 readFrameHi = (int32)ceil(fReadFrame); delayedFrame.channel[0] *= ((float)readFrameHi - fReadFrame); if(stereo) delayedFrame.channel[1] *= ((float)readFrameHi - fReadFrame); @@ -1462,7 +1462,7 @@ void FlangerNode::filterBuffer( hiFrame.channel[0] = ((float*)m_pDelayBuffer->data())[pos]; if(stereo) hiFrame.channel[1] = ((float*)m_pDelayBuffer->data())[pos+1]; - + // interpolate (B) delayedFrame.channel[0] += hiFrame.channel[0] * (fReadFrame - (float)readFrameLo); @@ -1472,11 +1472,11 @@ void FlangerNode::filterBuffer( } // mix back to output buffer - ((float*)input.data())[inPos] = + ((float*)input.data())[inPos] = (inFrame.channel[0] * (1.0-m_fMixRatio)) + (delayedFrame.channel[0] * m_fMixRatio); if(stereo) - ((float*)input.data())[inPos+1] = + ((float*)input.data())[inPos+1] = (inFrame.channel[1] * (1.0-m_fMixRatio)) + (delayedFrame.channel[1] * m_fMixRatio); @@ -1489,16 +1489,16 @@ void FlangerNode::filterBuffer( ((float*)m_pDelayBuffer->data())[delayWritePos+1] = inFrame.channel[1] + (delayedFrame.channel[1] * m_fFeedback); - + // advance write position if(++m_delayWriteFrame >= m_pDelayBuffer->frames()) m_delayWriteFrame = 0; // advance read offset ('LFO') m_fTheta += m_fThetaInc; - if(m_fTheta > 2*M_PI) - m_fTheta -= 2*M_PI; - + if(m_fTheta > 2 * M_PI) + m_fTheta -= 2 * M_PI; + // if(m_fDelayReadDelta < 0.0) { // if(m_fDelayReadOffset < m_fDelay) // m_fDelayReadDelta = -m_fDelayReadDelta; @@ -1510,32 +1510,30 @@ void FlangerNode::filterBuffer( } } -// figure the rate at which the (radial) read offset changes, -// based on the given sweep rate (in Hz) -float calc_sweep_delta( - const media_raw_audio_format& format, - float fRate) { - - return 2*PI * fRate / format.frame_rate; +/*! Figure the rate at which the (radial) read offset changes, + based on the given sweep rate (in Hz) +*/ +float +calc_sweep_delta(const media_raw_audio_format& format, float fRate) +{ + return 2 * M_PI * fRate / format.frame_rate; } -// figure the base delay (in frames) based on the given -// sweep delay/depth (in msec) - -float calc_sweep_base( - const media_raw_audio_format& format, - float fDelay, float fDepth) { - - return - (format.frame_rate * (fDelay + fDepth)) / 1000.0; +/*! Figure the base delay (in frames) based on the given + sweep delay/depth (in msec) +*/ +float +calc_sweep_base(const media_raw_audio_format& format, float delay, float depth) +{ + return (format.frame_rate * (delay + depth)) / 1000.0; } -float calc_sweep_factor( - const media_raw_audio_format& format, - float fDepth) { - return (format.frame_rate * fDepth) / 1000.0; +float +calc_sweep_factor(const media_raw_audio_format& format, float depth) +{ + return (format.frame_rate * depth) / 1000.0; } diff --git a/src/apps/fontdemo/FontDemoView.cpp b/src/apps/fontdemo/FontDemoView.cpp index 87dbff30f8..cfcc6da3e8 100644 --- a/src/apps/fontdemo/FontDemoView.cpp +++ b/src/apps/fontdemo/FontDemoView.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007, Haiku, Inc. All Rights Reserved. + * Copyright 2006-2009, Haiku, Inc. All Rights Reserved. * Distributed under the terms of the MIT License. * * Authors: @@ -8,17 +8,18 @@ #include "FontDemoView.h" -#include "messages.h" + +#include +#include +#include +#include #include #include #include #include -#include -#include -#include -#include +#include "messages.h" FontDemoView::FontDemoView(BRect rect) @@ -54,7 +55,8 @@ FontDemoView::~FontDemoView() void FontDemoView::FrameResized(float width, float height) { - // TODO: We shouldnt invalidate the whole view when bounding boxes are working as wanted + // TODO: We shouldnt invalidate the whole view when bounding boxes are + // working as wanted Invalidate(/*fBoxRegion.Frame()*/); BView::FrameResized(width, height); } @@ -78,9 +80,9 @@ FontDemoView::_DrawView(BView* view) { if (!view) return; - + view->SetDrawingMode(B_OP_COPY); - + BRect rect = view->Bounds(); view->SetHighColor(255, 255, 255); @@ -114,18 +116,18 @@ FontDemoView::_DrawView(BView* view) font_height fh; fFont.GetHeight(&fh); - float xCoordArray[size]; + float xCoordArray[size]; float yCoordArray[size]; float yCoord = (rect.Height() + fh.ascent - fh.descent) / 2; float xCoord = -rect.Width() / 2; const float xCenter = xCoord * -1; - const float r = Rotation() * (PI/180.0); + const float r = Rotation() * (M_PI / 180.0); const float cosinus = cos(r); const float sinus = -sin(r); // When the bounding boxes workes properly we will invalidate only the - // region area instead of the whole view. + // region area instead of the whole view. fBoxRegion.MakeEmpty(); @@ -135,7 +137,7 @@ FontDemoView::_DrawView(BView* view) yCoordArray[i] = sinus * (xCoord - xCoordArray[i]); xCoordArray[i] = cosinus * xCoord; - + xCoordArray[i] += xCenter; yCoordArray[i] += yCoord; @@ -234,7 +236,7 @@ FontDemoView::MessageReceived(BMessage* msg) case FONTSHEAR_MSG: { - float shear = 90.0; + float shear = 90.0; if (msg->FindFloat("_shear", &shear) == B_OK) { SetFontShear(shear); Invalidate(/*&fBoxRegion*/); @@ -244,7 +246,7 @@ FontDemoView::MessageReceived(BMessage* msg) case ROTATION_MSG: { - float rotation = 0.0; + float rotation = 0.0; if (msg->FindFloat("_rotation", &rotation) == B_OK) { SetFontRotation(rotation); Invalidate(/*&fBoxRegion*/); @@ -254,7 +256,7 @@ FontDemoView::MessageReceived(BMessage* msg) case SPACING_MSG: { - float space = 0.0; + float space = 0.0; if (msg->FindFloat("_spacing", &space) == B_OK) { SetSpacing(space); Invalidate(/*&fBoxRegion*/); @@ -264,13 +266,13 @@ FontDemoView::MessageReceived(BMessage* msg) case OUTLINE_MSG: { - int8 outline = 0; + int8 outline = 0; if (msg->FindInt8("_outline", &outline) == B_OK) { SetOutlineLevel(outline); Invalidate(/*&fBoxRegion*/); } break; - } + } case ALIASING_MSG: { @@ -281,7 +283,7 @@ FontDemoView::MessageReceived(BMessage* msg) } break; } - + case DRAWINGMODE_CHANGED_MSG: { if (msg->FindInt32("_mode", (int32 *)&fDrawingMode) == B_OK) { @@ -289,7 +291,7 @@ FontDemoView::MessageReceived(BMessage* msg) } break; } - + case BOUNDING_BOX_MSG: { bool boundingbox = false; @@ -299,7 +301,7 @@ FontDemoView::MessageReceived(BMessage* msg) } break; } - + default: BView::MessageReceived(msg); break; diff --git a/src/apps/icon-o-matic/generic/support/support.cpp b/src/apps/icon-o-matic/generic/support/support.cpp index 1f4b1195ae..77e1e3298e 100644 --- a/src/apps/icon-o-matic/generic/support/support.cpp +++ b/src/apps/icon-o-matic/generic/support/support.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2006, Haiku. + * Copyright 2006-2009, Haiku. * Distributed under the terms of the MIT License. * * Authors: @@ -16,17 +16,18 @@ #include #include + // point_line_distance double -point_line_distance(double x1, double y1, - double x2, double y2, - double x, double y) +point_line_distance(double x1, double y1, double x2, double y2, double x, + double y) { double dx = x2 - x1; double dy = y2 - y1; return ((x - x2) * dy - (y - y2) * dx) / sqrt(dx * dx + dy * dy); } + // point_line_distance double point_line_distance(BPoint point, BPoint pa, BPoint pb) @@ -42,41 +43,42 @@ point_line_distance(BPoint point, BPoint pa, BPoint pb) double alpha = acos((b*b + c*c - a*a) / (2*b*c)); double beta = acos((a*a + c*c - b*b) / (2*a*c)); - if (alpha <= PI2 && beta <= PI2) { + if (alpha <= M_PI_2 && beta <= M_PI_2) { currentDist = fabs(point_line_distance(pa.x, pa.y, pb.x, pb.y, - point.x, point.y)); + point.x, point.y)); } } return currentDist; } + // calc_angle double calc_angle(BPoint origin, BPoint from, BPoint to, bool degree) { double angle = 0.0; - double d = point_line_distance(from.x, from.y, - origin.x, origin.y, - to.x, to.y); + double d = point_line_distance(from.x, from.y, origin.x, origin.y, + to.x, to.y); if (d != 0.0) { double a = point_point_distance(from, to); double b = point_point_distance(from, origin); double c = point_point_distance(to, origin); if (a > 0.0 && b > 0.0 && c > 0.0) { angle = acos((b*b + c*c - a*a) / (2.0*b*c)); - + if (d < 0.0) angle = -angle; if (degree) - angle = angle * 180.0 / PI; + angle = angle * 180.0 / M_PI; } } return angle; } + // write_string status_t write_string(BPositionIO* stream, BString& string) @@ -91,6 +93,7 @@ write_string(BPositionIO* stream, BString& string) return written; } + // append_float void append_float(BString& string, float n, int32 maxDigits) @@ -127,10 +130,11 @@ append_float(BString& string, float n, int32 maxDigits) } } + //// gauss //double //gauss(double f) -//{ +//{ // // this aint' a real gauss function ///* if (f >= -1.0 && f <= 1.0) { // if (f < -0.5) { diff --git a/src/apps/icon-o-matic/transformable/CanvasTransformBox.cpp b/src/apps/icon-o-matic/transformable/CanvasTransformBox.cpp index 1620f014d2..129838a71a 100644 --- a/src/apps/icon-o-matic/transformable/CanvasTransformBox.cpp +++ b/src/apps/icon-o-matic/transformable/CanvasTransformBox.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2006, Haiku. + * Copyright 2006-2009, Haiku. * Distributed under the terms of the MIT License. * * Authors: @@ -10,20 +10,24 @@ #include "CanvasView.h" + // constructor CanvasTransformBox::CanvasTransformBox(CanvasView* view) - : TransformBox(view, BRect(0.0, 0.0, 1.0, 1.0)), + : + TransformBox(view, BRect(0.0, 0.0, 1.0, 1.0)), - fCanvasView(view), - fParentTransform() + fCanvasView(view), + fParentTransform() { } + // destructor CanvasTransformBox::~CanvasTransformBox() { } + // TransformFromCanvas void CanvasTransformBox::TransformFromCanvas(BPoint& point) const @@ -32,6 +36,7 @@ CanvasTransformBox::TransformFromCanvas(BPoint& point) const fCanvasView->ConvertFromCanvas(&point); } + // TransformToCanvas void CanvasTransformBox::TransformToCanvas(BPoint& point) const @@ -40,6 +45,7 @@ CanvasTransformBox::TransformToCanvas(BPoint& point) const fParentTransform.Transform(&point); } + // ZoomLevel float CanvasTransformBox::ZoomLevel() const @@ -47,11 +53,12 @@ CanvasTransformBox::ZoomLevel() const return fCanvasView->ZoomLevel(); } + // ViewSpaceRotation double CanvasTransformBox::ViewSpaceRotation() const { Transformable t(*this); t.Multiply(fParentTransform); - return t.rotation() * 180.0 / PI; + return t.rotation() * 180.0 / M_PI; } diff --git a/src/apps/icon-o-matic/transformable/ChannelTransform.cpp b/src/apps/icon-o-matic/transformable/ChannelTransform.cpp index 350c68877b..ce082863a3 100644 --- a/src/apps/icon-o-matic/transformable/ChannelTransform.cpp +++ b/src/apps/icon-o-matic/transformable/ChannelTransform.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2006, Haiku. + * Copyright 2006-2009, Haiku. * Distributed under the terms of the MIT License. * * Authors: @@ -11,33 +11,38 @@ #include #include + // constructor ChannelTransform::ChannelTransform() - : Transformable(), - fPivot(0.0, 0.0), - fTranslation(0.0, 0.0), - fRotation(0.0), - fXScale(1.0), - fYScale(1.0) + : + Transformable(), + fPivot(0.0, 0.0), + fTranslation(0.0, 0.0), + fRotation(0.0), + fXScale(1.0), + fYScale(1.0) { } // copy constructor ChannelTransform::ChannelTransform(const ChannelTransform& other) - : Transformable(other), - fPivot(other.fPivot), - fTranslation(other.fTranslation), - fRotation(other.fRotation), - fXScale(other.fXScale), - fYScale(other.fYScale) + : + Transformable(other), + fPivot(other.fPivot), + fTranslation(other.fTranslation), + fRotation(other.fRotation), + fXScale(other.fXScale), + fYScale(other.fYScale) { } + // destructor ChannelTransform::~ChannelTransform() { } + // SetTransformation void ChannelTransform::SetTransformation(const Transformable& other) @@ -63,13 +68,11 @@ ChannelTransform::SetTransformation(const Transformable& other) SetTransformation(B_ORIGIN, BPoint(tx, ty), rotation, scaleX, scaleY); } + // SetTransformation void -ChannelTransform::SetTransformation(BPoint pivot, - BPoint translation, - double rotation, - double xScale, - double yScale) +ChannelTransform::SetTransformation(BPoint pivot, BPoint translation, + double rotation, double xScale, double yScale) { //printf("SetTransformation(BPoint(%.1f, %.1f), BPoint(%.1f, %.1f), " //"%.2f, %.2f, %.2f)\n", pivot.x, pivot.y, translation.x, translation.y, @@ -86,11 +89,12 @@ ChannelTransform::SetTransformation(BPoint pivot, fRotation = rotation; fXScale = xScale; fYScale = yScale; - + _UpdateMatrix(); } } + // SetPivot void ChannelTransform::SetPivot(BPoint pivot) @@ -103,6 +107,7 @@ ChannelTransform::SetPivot(BPoint pivot) _UpdateMatrix(); } + // TranslateBy void ChannelTransform::TranslateBy(BPoint offset) @@ -115,10 +120,11 @@ ChannelTransform::TranslateBy(BPoint offset) _UpdateMatrix(); } + // RotateBy -// -// converts a rotation in world coordinates into -// a combined local rotation and a translation +/*! Converts a rotation in world coordinates into + a combined local rotation and a translation. +*/ void ChannelTransform::RotateBy(BPoint origin, double degrees) { @@ -133,7 +139,7 @@ ChannelTransform::RotateBy(BPoint origin, double degrees) double xOffset = fTranslation.x - origin.x; double yOffset = fTranslation.y - origin.y; - agg::trans_affine_rotation m(degrees * PI / 180.0); + agg::trans_affine_rotation m(degrees * M_PI / 180.0); m.transform(&xOffset, &yOffset); fTranslation.x = origin.x + xOffset; @@ -155,6 +161,7 @@ ChannelTransform::RotateBy(double degrees) _UpdateMatrix(); } + //// ScaleBy //// //// converts a scalation in world coordinates into @@ -191,10 +198,11 @@ ChannelTransform::ScaleBy(double xScale, double yScale) _UpdateMatrix(); } + // SetTranslationAndScale void -ChannelTransform::SetTranslationAndScale(BPoint offset, - double xScale, double yScale) +ChannelTransform::SetTranslationAndScale(BPoint offset, double xScale, + double yScale) { if (fTranslation == offset && fXScale == xScale && fYScale == yScale) return; @@ -207,6 +215,7 @@ ChannelTransform::SetTranslationAndScale(BPoint offset, _UpdateMatrix(); } + // Reset void ChannelTransform::Reset() @@ -214,6 +223,7 @@ ChannelTransform::Reset() SetTransformation(B_ORIGIN, B_ORIGIN, 0.0, 1.0, 1.0); } + // = ChannelTransform& ChannelTransform::operator=(const ChannelTransform& other) @@ -228,6 +238,7 @@ ChannelTransform::operator=(const ChannelTransform& other) return *this; } + // _UpdateMatrix void ChannelTransform::_UpdateMatrix() @@ -246,10 +257,10 @@ ChannelTransform::_UpdateMatrix() // coordinate system and is the center for rotation and scale multiply(agg::trans_affine_translation(-fPivot.x, -fPivot.y)); multiply(agg::trans_affine_scaling(xScale, yScale)); - multiply(agg::trans_affine_rotation(fRotation * PI / 180.0)); + multiply(agg::trans_affine_rotation(fRotation * M_PI / 180.0)); multiply(agg::trans_affine_translation(fPivot.x + fTranslation.x, - fPivot.y + fTranslation.y)); + fPivot.y + fTranslation.y)); // call hook function Update(); diff --git a/src/apps/icon-o-matic/transformable/TransformBox.cpp b/src/apps/icon-o-matic/transformable/TransformBox.cpp index 391dca0082..c3e96f07dc 100644 --- a/src/apps/icon-o-matic/transformable/TransformBox.cpp +++ b/src/apps/icon-o-matic/transformable/TransformBox.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2006-2007, Haiku. + * Copyright 2006-2009, Haiku. * Distributed under the terms of the MIT License. * * Authors: @@ -21,55 +21,66 @@ #include "StateView.h" #include "TransformCommand.h" + #define INSET 8.0 -TransformBoxListener::TransformBoxListener() {} -TransformBoxListener::~TransformBoxListener() {} + +TransformBoxListener::TransformBoxListener() +{ +} + + +TransformBoxListener::~TransformBoxListener() +{ +} + // #pragma mark - + // constructor TransformBox::TransformBox(StateView* view, BRect box) - : ChannelTransform(), - Manipulator(NULL), - fOriginalBox(box), + : + ChannelTransform(), + Manipulator(NULL), + fOriginalBox(box), - fLeftTop(box.LeftTop()), - fRightTop(box.RightTop()), - fLeftBottom(box.LeftBottom()), - fRightBottom(box.RightBottom()), + fLeftTop(box.LeftTop()), + fRightTop(box.RightTop()), + fLeftBottom(box.LeftBottom()), + fRightBottom(box.RightBottom()), - fPivot((fLeftTop.x + fRightBottom.x) / 2.0, - (fLeftTop.y + fRightBottom.y) / 2.0), - fPivotOffset(B_ORIGIN), + fPivot((fLeftTop.x + fRightBottom.x) / 2.0, + (fLeftTop.y + fRightBottom.y) / 2.0), + fPivotOffset(B_ORIGIN), + fCurrentCommand(NULL), + fCurrentState(NULL), - fCurrentCommand(NULL), - fCurrentState(NULL), + fDragging(false), + fMousePos(-10000.0, -10000.0), + fModifiers(0), - fDragging(false), - fMousePos(-10000.0, -10000.0), - fModifiers(0), + fNudging(false), - fNudging(false), + fView(view), - fView(view), + fDragLTState(new DragCornerState(this, DragCornerState::LEFT_TOP_CORNER)), + fDragRTState(new DragCornerState(this, DragCornerState::RIGHT_TOP_CORNER)), + fDragLBState(new DragCornerState(this, DragCornerState::LEFT_BOTTOM_CORNER)), + fDragRBState(new DragCornerState(this, DragCornerState::RIGHT_BOTTOM_CORNER)), - fDragLTState(new DragCornerState(this, DragCornerState::LEFT_TOP_CORNER)), - fDragRTState(new DragCornerState(this, DragCornerState::RIGHT_TOP_CORNER)), - fDragLBState(new DragCornerState(this, DragCornerState::LEFT_BOTTOM_CORNER)), - fDragRBState(new DragCornerState(this, DragCornerState::RIGHT_BOTTOM_CORNER)), + fDragLState(new DragSideState(this, DragSideState::LEFT_SIDE)), + fDragRState(new DragSideState(this, DragSideState::RIGHT_SIDE)), + fDragTState(new DragSideState(this, DragSideState::TOP_SIDE)), + fDragBState(new DragSideState(this, DragSideState::BOTTOM_SIDE)), - fDragLState(new DragSideState(this, DragSideState::LEFT_SIDE)), - fDragRState(new DragSideState(this, DragSideState::RIGHT_SIDE)), - fDragTState(new DragSideState(this, DragSideState::TOP_SIDE)), - fDragBState(new DragSideState(this, DragSideState::BOTTOM_SIDE)), - - fRotateState(new RotateBoxState(this)), - fTranslateState(new DragBoxState(this)), - fOffsetCenterState(new OffsetCenterState(this)) + fRotateState(new RotateBoxState(this)), + fTranslateState(new DragBoxState(this)), + fOffsetCenterState(new OffsetCenterState(this)) { } + // destructor TransformBox::~TransformBox() { @@ -92,6 +103,7 @@ TransformBox::~TransformBox() delete fOffsetCenterState; } + // Draw void TransformBox::Draw(BView* into, BRect updateRect) @@ -131,8 +143,10 @@ TransformBox::Draw(BView* into, BRect updateRect) into->SetDrawingMode(B_OP_COPY); } + // #pragma mark - + // MouseDown bool TransformBox::MouseDown(BPoint where) @@ -147,12 +161,13 @@ TransformBox::MouseDown(BPoint where) delete fCurrentCommand; fCurrentCommand = MakeCommand(fCurrentState->ActionName(), - fCurrentState->ActionNameIndex()); + fCurrentState->ActionNameIndex()); } return true; } + // MouseMoved void TransformBox::MouseMoved(BPoint where) @@ -170,6 +185,7 @@ TransformBox::MouseMoved(BPoint where) } } + // MouseUp Command* TransformBox::MouseUp() @@ -178,6 +194,7 @@ TransformBox::MouseUp() return FinishTransaction(); } + // MouseOver bool TransformBox::MouseOver(BPoint where) @@ -193,6 +210,7 @@ TransformBox::MouseOver(BPoint where) return false; } + // DoubleClicked bool TransformBox::DoubleClicked(BPoint where) @@ -200,8 +218,10 @@ TransformBox::DoubleClicked(BPoint where) return false; } + // #pragma mark - + // Bounds BRect TransformBox::Bounds() @@ -227,6 +247,7 @@ TransformBox::Bounds() return r; } + // TrackingBounds BRect TransformBox::TrackingBounds(BView* withinView) @@ -234,8 +255,10 @@ TransformBox::TrackingBounds(BView* withinView) return withinView->Bounds(); } + // #pragma mark - + // ModifiersChanged void TransformBox::ModifiersChanged(uint32 modifiers) @@ -246,6 +269,7 @@ TransformBox::ModifiersChanged(uint32 modifiers) } } + // HandleKeyDown bool TransformBox::HandleKeyDown(uint32 key, uint32 modifiers, Command** _command) @@ -270,7 +294,7 @@ TransformBox::HandleKeyDown(uint32 key, uint32 modifiers, Command** _command) case B_RIGHT_ARROW: translation.x = offset; break; - + default: handled = false; break; @@ -288,6 +312,7 @@ TransformBox::HandleKeyDown(uint32 key, uint32 modifiers, Command** _command) return true; } + // HandleKeyUp bool TransformBox::HandleKeyUp(uint32 key, uint32 modifiers, Command** _command) @@ -299,6 +324,7 @@ TransformBox::HandleKeyUp(uint32 key, uint32 modifiers, Command** _command) return false; } + // UpdateCursor bool TransformBox::UpdateCursor() @@ -310,8 +336,10 @@ TransformBox::UpdateCursor() return false; } + // #pragma mark - + // AttachedToView void TransformBox::AttachedToView(BView* view) @@ -319,6 +347,7 @@ TransformBox::AttachedToView(BView* view) view->Invalidate(Bounds().InsetByCopy(-INSET, -INSET)); } + // DetachedFromView void TransformBox::DetachedFromView(BView* view) @@ -326,8 +355,10 @@ TransformBox::DetachedFromView(BView* view) view->Invalidate(Bounds().InsetByCopy(-INSET, -INSET)); } + // pragma mark - + // Update void TransformBox::Update(bool deep) @@ -352,6 +383,7 @@ TransformBox::Update(bool deep) Transform(&fPivot); } + // OffsetCenter void TransformBox::OffsetCenter(BPoint offset) @@ -362,6 +394,7 @@ TransformBox::OffsetCenter(BPoint offset) } } + // Center BPoint TransformBox::Center() const @@ -369,6 +402,7 @@ TransformBox::Center() const return fPivot; } + // SetBox void TransformBox::SetBox(BRect box) @@ -379,22 +413,21 @@ TransformBox::SetBox(BRect box) } } + // FinishTransaction Command* TransformBox::FinishTransaction() { Command* command = fCurrentCommand; if (fCurrentCommand) { - fCurrentCommand->SetNewTransformation(Pivot(), - Translation(), - LocalRotation(), - LocalXScale(), - LocalYScale()); + fCurrentCommand->SetNewTransformation(Pivot(), Translation(), + LocalRotation(), LocalXScale(), LocalYScale()); fCurrentCommand = NULL; } return command; } + // NudgeBy void TransformBox::NudgeBy(BPoint offset) @@ -408,6 +441,7 @@ TransformBox::NudgeBy(BPoint offset) } } + // FinishNudging Command* TransformBox::FinishNudging() @@ -416,18 +450,21 @@ TransformBox::FinishNudging() return FinishTransaction(); } + // TransformFromCanvas void TransformBox::TransformFromCanvas(BPoint& point) const { } + // TransformToCanvas void TransformBox::TransformToCanvas(BPoint& point) const { } + // ZoomLevel float TransformBox::ZoomLevel() const @@ -435,6 +472,7 @@ TransformBox::ZoomLevel() const return 1.0; } + // ViewSpaceRotation double TransformBox::ViewSpaceRotation() const @@ -443,8 +481,10 @@ TransformBox::ViewSpaceRotation() const return LocalRotation(); } + // #pragma mark - + // AddListener bool TransformBox::AddListener(TransformBoxListener* listener) @@ -454,6 +494,7 @@ TransformBox::AddListener(TransformBoxListener* listener) return false; } + // RemoveListener bool TransformBox::RemoveListener(TransformBoxListener* listener) @@ -461,30 +502,29 @@ TransformBox::RemoveListener(TransformBoxListener* listener) return fListeners.RemoveItem((void*)listener); } + // #pragma mark - + // TODO: why another version? // point_line_dist float point_line_dist(BPoint start, BPoint end, BPoint p, float radius) { - BRect r(min_c(start.x, end.x), - min_c(start.y, end.y), - max_c(start.x, end.x), - max_c(start.y, end.y)); + BRect r(min_c(start.x, end.x), min_c(start.y, end.y), max_c(start.x, end.x), + max_c(start.y, end.y)); r.InsetBy(-radius, -radius); if (r.Contains(p)) { - return fabs(agg::calc_line_point_distance(start.x, start.y, - end.x, end.y, - p.x, p.y)); + return fabs(agg::calc_line_point_distance(start.x, start.y, end.x, end.y, + p.x, p.y)); } - return min_c(point_point_distance(start, p), - point_point_distance(end, p)); + + return min_c(point_point_distance(start, p), point_point_distance(end, p)); } + // _DragStateFor -// -// where is expected in canvas view coordinates +//! where is expected in canvas view coordinates DragState* TransformBox::_DragStateFor(BPoint where, float canvasZoom) { @@ -586,6 +626,7 @@ TransformBox::_DragStateFor(BPoint where, float canvasZoom) return state; } + // _StrokeBWLine void TransformBox::_StrokeBWLine(BView* into, BPoint from, BPoint to) const @@ -617,6 +658,7 @@ TransformBox::_StrokeBWLine(BView* into, BPoint from, BPoint to) const into->StrokeLine(from, to, B_SOLID_HIGH); } + // _StrokeBWPoint void TransformBox::_StrokeBWPoint(BView* into, BPoint point, double angle) const @@ -638,7 +680,7 @@ TransformBox::_StrokeBWPoint(BView* into, BPoint point, double angle) const double xOffset = -x; double yOffset = -y; - agg::trans_affine_rotation r(angle * PI / 180.0); + agg::trans_affine_rotation r(angle * M_PI / 180.0); r.transform(&xOffset, &yOffset); xOffset = x + xOffset; @@ -666,8 +708,10 @@ TransformBox::_StrokeBWPoint(BView* into, BPoint point, double angle) const into->StrokeLine(p[3], p[0], B_SOLID_LOW); } + // #pragma mark - + // _NotifyDeleted void TransformBox::_NotifyDeleted() const @@ -681,8 +725,10 @@ TransformBox::_NotifyDeleted() const } } + // #pragma mark - + // _SetState void TransformBox::_SetState(DragState* state) diff --git a/src/apps/icon-o-matic/transformable/TransformBoxStates.cpp b/src/apps/icon-o-matic/transformable/TransformBoxStates.cpp index 1ce9b718ee..bfa023e9b3 100644 --- a/src/apps/icon-o-matic/transformable/TransformBoxStates.cpp +++ b/src/apps/icon-o-matic/transformable/TransformBoxStates.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2006, Haiku. + * Copyright 2006-2009, Haiku. * Distributed under the terms of the MIT License. * * Authors: @@ -19,15 +19,17 @@ #include "support.h" #include "TransformBox.h" -//#include "Strings.h" + // constructor DragState::DragState(TransformBox* parent) - : fOrigin(0.0, 0.0), - fParent(parent) + : + fOrigin(0.0, 0.0), + fParent(parent) { } + // SetOrigin void DragState::SetOrigin(BPoint origin) @@ -35,6 +37,7 @@ DragState::SetOrigin(BPoint origin) fOrigin = origin; } + // ActionName const char* DragState::ActionName() const @@ -42,6 +45,7 @@ DragState::ActionName() const return "Transformation"; } + // ActionNameIndex uint32 DragState::ActionNameIndex() const @@ -49,6 +53,7 @@ DragState::ActionNameIndex() const return TRANSFORMATION; } + // _SetViewCursor void DragState::_SetViewCursor(BView* view, const uchar* cursorData) const @@ -57,15 +62,19 @@ DragState::_SetViewCursor(BView* view, const uchar* cursorData) const view->SetViewCursor(&cursor); } + // #pragma mark - DragCornerState + // constructor DragCornerState::DragCornerState(TransformBox* parent, uint32 corner) - : DragState(parent), - fCorner(corner) + : + DragState(parent), + fCorner(corner) { } + // SetOrigin void DragCornerState::SetOrigin(BPoint origin) @@ -78,9 +87,10 @@ DragCornerState::SetOrigin(BPoint origin) // copy the matrix at the start of the drag procedure fMatrix.reset(); fMatrix.multiply(agg::trans_affine_scaling(fOldXScale, fOldYScale)); - fMatrix.multiply(agg::trans_affine_rotation(fParent->LocalRotation() * PI / 180.0)); + fMatrix.multiply(agg::trans_affine_rotation(fParent->LocalRotation() + * M_PI / 180.0)); fMatrix.multiply(agg::trans_affine_translation(fParent->Translation().x, - fParent->Translation().y)); + fParent->Translation().y)); double x = origin.x; double y = origin.y; @@ -125,6 +135,8 @@ DragCornerState::SetOrigin(BPoint origin) } DragState::SetOrigin(origin); } + + // DragTo void DragCornerState::DragTo(BPoint current, uint32 modifiers) @@ -164,11 +176,11 @@ DragCornerState::DragTo(BPoint current, uint32 modifiers) translation.x = x; translation.y = y; - fParent->SetTranslationAndScale(translation, - xScale * fOldXScale, - yScale * fOldYScale); + fParent->SetTranslationAndScale(translation, xScale * fOldXScale, + yScale * fOldYScale); } + // UpdateViewCursor void DragCornerState::UpdateViewCursor(BView* view, BPoint current) const @@ -180,91 +192,98 @@ DragCornerState::UpdateViewCursor(BView* view, BPoint current) const switch (fCorner) { case LEFT_TOP_CORNER: case RIGHT_BOTTOM_CORNER: - if (flipX) - _SetViewCursor(view, flipY ? kLeftTopRightBottomCursor - : kLeftBottomRightTopCursor); - else - _SetViewCursor(view, flipY ? kLeftBottomRightTopCursor - : kLeftTopRightBottomCursor); + if (flipX) { + _SetViewCursor(view, flipY + ? kLeftTopRightBottomCursor : kLeftBottomRightTopCursor); + } else { + _SetViewCursor(view, flipY + ? kLeftBottomRightTopCursor : kLeftTopRightBottomCursor); + } break; case RIGHT_TOP_CORNER: case LEFT_BOTTOM_CORNER: - if (flipX) - _SetViewCursor(view, flipY ? kLeftBottomRightTopCursor - : kLeftTopRightBottomCursor); - else - _SetViewCursor(view, flipY ? kLeftTopRightBottomCursor - : kLeftBottomRightTopCursor); + if (flipX) { + _SetViewCursor(view, flipY + ? kLeftBottomRightTopCursor : kLeftTopRightBottomCursor); + } else { + _SetViewCursor(view, flipY + ? kLeftTopRightBottomCursor : kLeftBottomRightTopCursor); + } break; } } else if (rotation < 90.0) { switch (fCorner) { case LEFT_TOP_CORNER: case RIGHT_BOTTOM_CORNER: - if (flipX) - _SetViewCursor(view, flipY ? kLeftRightCursor - : kUpDownCursor); - else - _SetViewCursor(view, flipY ? kUpDownCursor - : kLeftRightCursor); + if (flipX) { + _SetViewCursor(view, + flipY ? kLeftRightCursor : kUpDownCursor); + } else { + _SetViewCursor(view, + flipY ? kUpDownCursor : kLeftRightCursor); + } break; case RIGHT_TOP_CORNER: case LEFT_BOTTOM_CORNER: - if (flipX) - _SetViewCursor(view, flipY ? kUpDownCursor - : kLeftRightCursor); - else - _SetViewCursor(view, flipY ? kLeftRightCursor - : kUpDownCursor); + if (flipX) { + _SetViewCursor(view, + flipY ? kUpDownCursor : kLeftRightCursor); + } else { + _SetViewCursor(view, + flipY ? kLeftRightCursor : kUpDownCursor); + } break; } } else if (rotation < 135.0) { switch (fCorner) { case LEFT_TOP_CORNER: case RIGHT_BOTTOM_CORNER: - if (flipX) - _SetViewCursor(view, flipY ? kLeftBottomRightTopCursor - : kLeftTopRightBottomCursor); - else - _SetViewCursor(view, flipY ? kLeftTopRightBottomCursor - : kLeftBottomRightTopCursor); - break; + if (flipX) { + _SetViewCursor(view, flipY + ? kLeftBottomRightTopCursor : kLeftTopRightBottomCursor); + } else { + _SetViewCursor(view, flipY + ? kLeftTopRightBottomCursor : kLeftBottomRightTopCursor); + } break; case RIGHT_TOP_CORNER: case LEFT_BOTTOM_CORNER: - if (flipX) - _SetViewCursor(view, flipY ? kLeftTopRightBottomCursor - : kLeftBottomRightTopCursor); - else - _SetViewCursor(view, flipY ? kLeftBottomRightTopCursor - : kLeftTopRightBottomCursor); - break; + if (flipX) { + _SetViewCursor(view, flipY + ? kLeftTopRightBottomCursor : kLeftBottomRightTopCursor); + } else { + _SetViewCursor(view, flipY + ? kLeftBottomRightTopCursor : kLeftTopRightBottomCursor); + } break; } } else { switch (fCorner) { case LEFT_TOP_CORNER: case RIGHT_BOTTOM_CORNER: - if (flipX) - _SetViewCursor(view, flipY ? kUpDownCursor - : kLeftRightCursor); - else - _SetViewCursor(view, flipY ? kLeftRightCursor - : kUpDownCursor); + if (flipX) { + _SetViewCursor(view, + flipY ? kUpDownCursor : kLeftRightCursor); + } else { + _SetViewCursor(view, + flipY ? kLeftRightCursor : kUpDownCursor); + } break; case RIGHT_TOP_CORNER: case LEFT_BOTTOM_CORNER: - if (flipX) - _SetViewCursor(view, flipY ? kLeftRightCursor - : kUpDownCursor); - else - _SetViewCursor(view, flipY ? kUpDownCursor - : kLeftRightCursor); + if (flipX) { + _SetViewCursor(view, + flipY ? kLeftRightCursor : kUpDownCursor); + } else { + _SetViewCursor(view, + flipY ? kUpDownCursor : kLeftRightCursor); + } break; } } } + // ActionName const char* DragCornerState::ActionName() const @@ -272,6 +291,7 @@ DragCornerState::ActionName() const return "Scale"; } + // ActionNameIndex uint32 DragCornerState::ActionNameIndex() const @@ -282,12 +302,15 @@ DragCornerState::ActionNameIndex() const // #pragma mark - DragSideState + DragSideState::DragSideState(TransformBox* parent, uint32 side) - : DragState(parent), - fSide(side) + : + DragState(parent), + fSide(side) { } + // SetOrigin void DragSideState::SetOrigin(BPoint origin) @@ -300,9 +323,10 @@ DragSideState::SetOrigin(BPoint origin) // copy the matrix at the start of the drag procedure fMatrix.reset(); fMatrix.multiply(agg::trans_affine_scaling(fOldXScale, fOldYScale)); - fMatrix.multiply(agg::trans_affine_rotation(fParent->LocalRotation() * PI / 180.0)); + fMatrix.multiply(agg::trans_affine_rotation(fParent->LocalRotation() + * M_PI / 180.0)); fMatrix.multiply(agg::trans_affine_translation(fParent->Translation().x, - fParent->Translation().y)); + fParent->Translation().y)); double x = origin.x; double y = origin.y; @@ -336,6 +360,7 @@ DragSideState::SetOrigin(BPoint origin) DragState::SetOrigin(origin); } + // DragTo void DragSideState::DragTo(BPoint current, uint32 modifiers) @@ -369,11 +394,11 @@ DragSideState::DragTo(BPoint current, uint32 modifiers) translation.x = x; translation.y = y; - fParent->SetTranslationAndScale(translation, - xScale * fOldXScale, - yScale * fOldYScale); + fParent->SetTranslationAndScale(translation, xScale * fOldXScale, + yScale * fOldYScale); } + // UpdateViewCursor void DragSideState::UpdateViewCursor(BView* view, BPoint current) const @@ -426,6 +451,7 @@ DragSideState::UpdateViewCursor(BView* view, BPoint current) const } } + // ActionName const char* DragSideState::ActionName() const @@ -433,6 +459,7 @@ DragSideState::ActionName() const return "Scale"; } + // ActionNameIndex uint32 DragSideState::ActionNameIndex() const @@ -443,6 +470,7 @@ DragSideState::ActionNameIndex() const // #pragma mark - DragBoxState + // SetOrigin void DragBoxState::SetOrigin(BPoint origin) @@ -451,6 +479,7 @@ DragBoxState::SetOrigin(BPoint origin) DragState::SetOrigin(origin); } + // DragTo void DragBoxState::DragTo(BPoint current, uint32 modifiers) @@ -466,6 +495,7 @@ DragBoxState::DragTo(BPoint current, uint32 modifiers) fParent->TranslateBy(newTranslation - fParent->Translation()); } + // UpdateViewCursor void DragBoxState::UpdateViewCursor(BView* view, BPoint current) const @@ -473,6 +503,7 @@ DragBoxState::UpdateViewCursor(BView* view, BPoint current) const _SetViewCursor(view, kMoveCursor); } + // ActionName const char* DragBoxState::ActionName() const @@ -480,6 +511,7 @@ DragBoxState::ActionName() const return "Move"; } + // ActionNameIndex uint32 DragBoxState::ActionNameIndex() const @@ -490,13 +522,16 @@ DragBoxState::ActionNameIndex() const // #pragma mark - RotateBoxState + // constructor RotateBoxState::RotateBoxState(TransformBox* parent) - : DragState(parent), - fOldAngle(0.0) + : + DragState(parent), + fOldAngle(0.0) { } + // SetOrigin void RotateBoxState::SetOrigin(BPoint origin) @@ -505,6 +540,7 @@ RotateBoxState::SetOrigin(BPoint origin) fOldAngle = fParent->LocalRotation(); } + // DragTo void RotateBoxState::DragTo(BPoint current, uint32 modifiers) @@ -524,6 +560,7 @@ RotateBoxState::DragTo(BPoint current, uint32 modifiers) fParent->RotateBy(fParent->Center(), newAngle - fParent->LocalRotation()); } + // UpdateViewCursor void RotateBoxState::UpdateViewCursor(BView* view, BPoint current) const @@ -531,8 +568,8 @@ RotateBoxState::UpdateViewCursor(BView* view, BPoint current) const BPoint origin(fParent->Center()); fParent->TransformToCanvas(origin); fParent->TransformToCanvas(current); - BPoint from = origin + BPoint(sinf(22.5 * 180.0 / PI) * 50.0, - -cosf(22.5 * 180.0 / PI) * 50.0); + BPoint from = origin + BPoint(sinf(22.5 * 180.0 / M_PI) * 50.0, + -cosf(22.5 * 180.0 / M_PI) * 50.0); float rotation = calc_angle(origin, from, current) + 180.0; @@ -555,6 +592,7 @@ RotateBoxState::UpdateViewCursor(BView* view, BPoint current) const } } + // ActionName const char* RotateBoxState::ActionName() const @@ -562,6 +600,7 @@ RotateBoxState::ActionName() const return "Rotate"; } + // ActionNameIndex uint32 RotateBoxState::ActionNameIndex() const @@ -570,9 +609,9 @@ RotateBoxState::ActionNameIndex() const } - // #pragma mark - OffsetCenterState + // SetOrigin void OffsetCenterState::SetOrigin(BPoint origin) @@ -591,6 +630,7 @@ OffsetCenterState::DragTo(BPoint current, uint32 modifiers) fOrigin = current; } + // UpdateViewCursor void OffsetCenterState::UpdateViewCursor(BView* view, BPoint current) const @@ -598,6 +638,7 @@ OffsetCenterState::UpdateViewCursor(BView* view, BPoint current) const _SetViewCursor(view, kPathMoveCursor); } + // ActionName const char* OffsetCenterState::ActionName() const @@ -605,11 +646,10 @@ OffsetCenterState::ActionName() const return "Move Pivot"; } + // ActionNameIndex uint32 OffsetCenterState::ActionNameIndex() const { return MOVE_PIVOT; } - - diff --git a/src/apps/icon-o-matic/transformable/TransformGradientBox.cpp b/src/apps/icon-o-matic/transformable/TransformGradientBox.cpp index c9ac0d3a8f..d8848a9c89 100644 --- a/src/apps/icon-o-matic/transformable/TransformGradientBox.cpp +++ b/src/apps/icon-o-matic/transformable/TransformGradientBox.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2006, Haiku. + * Copyright 2006-2009, Haiku. * Distributed under the terms of the MIT License. * * Authors: @@ -20,16 +20,17 @@ using std::nothrow; + // constructor -TransformGradientBox::TransformGradientBox(CanvasView* view, - Gradient* gradient, - Shape* parentShape) - : TransformBox(view, BRect(0.0, 0.0, 1.0, 1.0)), +TransformGradientBox::TransformGradientBox(CanvasView* view, Gradient* gradient, + Shape* parentShape) + : + TransformBox(view, BRect(0.0, 0.0, 1.0, 1.0)), - fCanvasView(view), + fCanvasView(view), - fShape(parentShape), - fGradient(gradient) + fShape(parentShape), + fGradient(gradient) { if (fShape) { fShape->Acquire(); @@ -43,6 +44,7 @@ TransformGradientBox::TransformGradientBox(CanvasView* view, } } + // destructor TransformGradientBox::~TransformGradientBox() { @@ -54,6 +56,7 @@ TransformGradientBox::~TransformGradientBox() fGradient->RemoveObserver(this); } + // Update void TransformGradientBox::Update(bool deep) @@ -87,6 +90,7 @@ TransformGradientBox::Update(bool deep) fGradient->AddObserver(this); } + // ObjectChanged void TransformGradientBox::ObjectChanged(const Observable* object) @@ -112,6 +116,7 @@ TransformGradientBox::ObjectChanged(const Observable* object) fView->UnlockLooper(); } + // Perform Command* TransformGradientBox::Perform() @@ -119,6 +124,7 @@ TransformGradientBox::Perform() return NULL; } + // Cancel Command* TransformGradientBox::Cancel() @@ -128,6 +134,7 @@ TransformGradientBox::Cancel() return NULL; } + // TransformFromCanvas void TransformGradientBox::TransformFromCanvas(BPoint& point) const @@ -137,6 +144,7 @@ TransformGradientBox::TransformFromCanvas(BPoint& point) const fCanvasView->ConvertFromCanvas(&point); } + // TransformToCanvas void TransformGradientBox::TransformToCanvas(BPoint& point) const @@ -146,6 +154,7 @@ TransformGradientBox::TransformToCanvas(BPoint& point) const fShape->Transform(&point); } + // ZoomLevel float TransformGradientBox::ZoomLevel() const @@ -153,6 +162,7 @@ TransformGradientBox::ZoomLevel() const return fCanvasView->ZoomLevel(); } + // ViewSpaceRotation double TransformGradientBox::ViewSpaceRotation() const @@ -160,25 +170,19 @@ TransformGradientBox::ViewSpaceRotation() const Transformable t(*this); if (fShape) t.Multiply(*fShape); - return t.rotation() * 180.0 / PI; + return t.rotation() * 180.0 / M_PI; } + // MakeCommand TransformCommand* TransformGradientBox::MakeCommand(const char* commandName, uint32 nameIndex) { Transformable* objects[1]; objects[0] = fGradient; - - return new TransformObjectsCommand(this, objects, fOriginals, 1, - Pivot(), - Translation(), - LocalRotation(), - LocalXScale(), - LocalYScale(), - - commandName, - nameIndex); + return new TransformObjectsCommand(this, objects, fOriginals, 1, Pivot(), + Translation(), LocalRotation(), LocalXScale(), LocalYScale(), commandName, + nameIndex); } diff --git a/src/libs/icon/shape/VectorPath.cpp b/src/libs/icon/shape/VectorPath.cpp index a2108426ae..87c317dbed 100644 --- a/src/libs/icon/shape/VectorPath.cpp +++ b/src/libs/icon/shape/VectorPath.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2006, Haiku. + * Copyright 2006-2009, Haiku. * Distributed under the terms of the MIT License. * * Authors: @@ -19,56 +19,51 @@ #include #ifdef ICON_O_MATIC -#include -#include +# include +# include #endif // ICON_O_MATIC #include #include #ifdef ICON_O_MATIC -# include "support.h" +# include "support.h" -# include "CommonPropertyIDs.h" -# include "IconProperty.h" -# include "Icons.h" -# include "Property.h" -# include "PropertyObject.h" +# include "CommonPropertyIDs.h" +# include "IconProperty.h" +# include "Icons.h" +# include "Property.h" +# include "PropertyObject.h" #endif // ICON_O_MATIC #include "Transformable.h" + #define obj_new(type, n) ((type *)malloc ((n) * sizeof(type))) #define obj_renew(p, type, n) ((type *)realloc (p, (n) * sizeof(type))) #define obj_free free #define ALLOC_CHUNKS 20 -// get_path_storage + bool -get_path_storage(agg::path_storage& path, - const control_point* points, int32 count, bool closed) +get_path_storage(agg::path_storage& path, const control_point* points, + int32 count, bool closed) { if (count > 1) { - path.move_to(points[0].point.x, - points[0].point.y); + path.move_to(points[0].point.x, points[0].point.y); for (int32 i = 1; i < count; i++) { - path.curve4(points[i - 1].point_out.x, - points[i - 1].point_out.y, - points[i].point_in.x, - points[i].point_in.y, - points[i].point.x, - points[i].point.y); + path.curve4(points[i - 1].point_out.x, points[i - 1].point_out.y, + points[i].point_in.x, points[i].point_in.y, + points[i].point.x, points[i].point.y); } if (closed) { // curve from last to first control point - path.curve4(points[count - 1].point_out.x, - points[count - 1].point_out.y, - points[0].point_in.x, - points[0].point_in.y, - points[0].point.x, - points[0].point.y); + path.curve4( + points[count - 1].point_out.x, points[count - 1].point_out.y, + points[0].point_in.x, points[0].point_in.y, + points[0].point.x, points[0].point.y); path.close_polygon(); } @@ -77,64 +72,70 @@ get_path_storage(agg::path_storage& path, return false; } -// #pragma mark - - -#ifdef ICON_O_MATIC -PathListener::PathListener() {} -PathListener::~PathListener() {} -#endif // #pragma mark - -// constructor -VectorPath::VectorPath() + #ifdef ICON_O_MATIC - : BArchivable(), - IconObject(""), - fListeners(20), -#else - : -#endif - fPath(NULL), - fClosed(false), - fPointCount(0), - fAllocCount(0), - fCachedBounds(0.0, 0.0, -1.0, -1.0) +PathListener::PathListener() { } -// constructor -VectorPath::VectorPath(const VectorPath& from) -#ifdef ICON_O_MATIC - : BArchivable(), - IconObject(from), - fListeners(20), -#else - : + +PathListener::~PathListener() +{ +} #endif - fPath(NULL), - fClosed(false), - fPointCount(0), - fAllocCount(0), - fCachedBounds(0.0, 0.0, -1.0, -1.0) + + +// #pragma mark - + + +VectorPath::VectorPath() + : +#ifdef ICON_O_MATIC + BArchivable(), + IconObject(""), + fListeners(20), +#endif + fPath(NULL), + fClosed(false), + fPointCount(0), + fAllocCount(0), + fCachedBounds(0.0, 0.0, -1.0, -1.0) +{ +} + + +VectorPath::VectorPath(const VectorPath& from) + : +#ifdef ICON_O_MATIC + BArchivable(), + IconObject(from), + fListeners(20), +#endif + fPath(NULL), + fClosed(false), + fPointCount(0), + fAllocCount(0), + fCachedBounds(0.0, 0.0, -1.0, -1.0) { *this = from; } -// constructor + VectorPath::VectorPath(BMessage* archive) -#ifdef ICON_O_MATIC - : BArchivable(), - IconObject(archive), - fListeners(20), -#else : +#ifdef ICON_O_MATIC + BArchivable(), + IconObject(archive), + fListeners(20), #endif - fPath(NULL), - fClosed(false), - fPointCount(0), - fAllocCount(0), - fCachedBounds(0.0, 0.0, -1.0, -1.0) + fPath(NULL), + fClosed(false), + fPointCount(0), + fAllocCount(0), + fCachedBounds(0.0, 0.0, -1.0, -1.0) { if (!archive) return; @@ -144,7 +145,6 @@ VectorPath::VectorPath(BMessage* archive) if (archive->GetInfo("point", &typeFound, &countFound) >= B_OK && typeFound == B_POINT_TYPE && _SetPointCount(countFound)) { - memset(fPath, 0, fAllocCount * sizeof(control_point)); BPoint point; @@ -152,10 +152,10 @@ VectorPath::VectorPath(BMessage* archive) BPoint pointOut; bool connected; for (int32 i = 0; i < fPointCount - && archive->FindPoint("point", i, &point) >= B_OK - && archive->FindPoint("point in", i, &pointIn) >= B_OK - && archive->FindPoint("point out", i, &pointOut) >= B_OK - && archive->FindBool("connected", i, &connected) >= B_OK; i++) { + && archive->FindPoint("point", i, &point) >= B_OK + && archive->FindPoint("point in", i, &pointIn) >= B_OK + && archive->FindPoint("point out", i, &pointOut) >= B_OK + && archive->FindBool("connected", i, &connected) >= B_OK; i++) { fPath[i].point = point; fPath[i].point_in = pointIn; fPath[i].point_out = pointOut; @@ -167,7 +167,7 @@ VectorPath::VectorPath(BMessage* archive) } -// destructor + VectorPath::~VectorPath() { if (fPath) @@ -185,11 +185,12 @@ VectorPath::~VectorPath() #endif } + // #pragma mark - + #ifdef ICON_O_MATIC -// MakePropertyObject PropertyObject* VectorPath::MakePropertyObject() const { @@ -204,27 +205,22 @@ VectorPath::MakePropertyObject() const BMessage* archive = new BMessage(); if (Archive(archive) == B_OK) { object->AddProperty(new IconProperty(PROPERTY_PATH, - kPathPropertyIconBits, - kPathPropertyIconWidth, - kPathPropertyIconHeight, - kPathPropertyIconFormat, - archive)); + kPathPropertyIconBits, kPathPropertyIconWidth, + kPathPropertyIconHeight, kPathPropertyIconFormat, archive)); } return object; } -// SetToPropertyObject + bool VectorPath::SetToPropertyObject(const PropertyObject* object) { AutoNotificationSuspender _(this); IconObject::SetToPropertyObject(object); - // closed SetClosed(object->Value(PROPERTY_CLOSED, fClosed)); - // archived path IconProperty* pathProperty = dynamic_cast( object->FindProperty(PROPERTY_PATH)); if (pathProperty && pathProperty->Message()) { @@ -235,61 +231,72 @@ VectorPath::SetToPropertyObject(const PropertyObject* object) return HasPendingNotifications(); } -// Archive + status_t VectorPath::Archive(BMessage* into, bool deep) const { status_t ret = IconObject::Archive(into, deep); - if (ret < B_OK) + if (ret != B_OK) return ret; if (fPointCount > 0) { // improve BMessage efficency by preallocating storage for all points // with the first call ret = into->AddData("point", B_POINT_TYPE, &fPath[0].point, - sizeof(BPoint), true, fPointCount); - if (ret >= B_OK) + sizeof(BPoint), true, fPointCount); + if (ret >= B_OK) { ret = into->AddData("point in", B_POINT_TYPE, &fPath[0].point_in, - sizeof(BPoint), true, fPointCount); - if (ret >= B_OK) + sizeof(BPoint), true, fPointCount); + } + if (ret >= B_OK) { ret = into->AddData("point out", B_POINT_TYPE, &fPath[0].point_out, - sizeof(BPoint), true, fPointCount); - if (ret >= B_OK) + sizeof(BPoint), true, fPointCount); + } + if (ret >= B_OK) { ret = into->AddData("connected", B_BOOL_TYPE, &fPath[0].connected, - sizeof(bool), true, fPointCount); + sizeof(bool), true, fPointCount); + } + // add the rest of the points for (int32 i = 1; i < fPointCount && ret >= B_OK; i++) { - ret = into->AddData("point", B_POINT_TYPE, &fPath[i].point, sizeof(BPoint)); - if (ret >= B_OK) - ret = into->AddData("point in", B_POINT_TYPE, &fPath[i].point_in, sizeof(BPoint)); - if (ret >= B_OK) - ret = into->AddData("point out", B_POINT_TYPE, &fPath[i].point_out, sizeof(BPoint)); - if (ret >= B_OK) - ret = into->AddData("connected", B_BOOL_TYPE, &fPath[i].connected, sizeof(bool)); + ret = into->AddData("point", B_POINT_TYPE, &fPath[i].point, + sizeof(BPoint)); + if (ret >= B_OK) { + ret = into->AddData("point in", B_POINT_TYPE, &fPath[i].point_in, + sizeof(BPoint)); + } + if (ret >= B_OK) { + ret = into->AddData("point out", B_POINT_TYPE, + &fPath[i].point_out, sizeof(BPoint)); + } + if (ret >= B_OK) { + ret = into->AddData("connected", B_BOOL_TYPE, + &fPath[i].connected, sizeof(bool)); + } } } - - if (ret >= B_OK) { + + if (ret >= B_OK) ret = into->AddBool("path closed", fClosed); - } else { + else fprintf(stderr, "failed adding points!\n"); - } - if (ret < B_OK) { + + if (ret < B_OK) fprintf(stderr, "failed adding close!\n"); - } + // finish off - if (ret < B_OK) { + if (ret < B_OK) ret = into->AddString("class", "VectorPath"); - } return ret; } #endif // ICON_O_MATIC + // #pragma mark - -// operator= + VectorPath& VectorPath::operator=(const VectorPath& from) { @@ -305,20 +312,21 @@ VectorPath::operator=(const VectorPath& from) fCachedBounds.Set(0.0, 0.0, -1.0, -1.0); } Notify(); - + return *this; } -// MakeEmpty + void VectorPath::MakeEmpty() { _SetPointCount(0); } + // #pragma mark - -// AddPoint + bool VectorPath::AddPoint(BPoint point) { @@ -333,12 +341,10 @@ VectorPath::AddPoint(BPoint point) return false; } -// AddPoint + bool -VectorPath::AddPoint(const BPoint& point, - const BPoint& pointIn, - const BPoint& pointOut, - bool connected) +VectorPath::AddPoint(const BPoint& point, const BPoint& pointIn, + const BPoint& pointOut, bool connected) { int32 index = fPointCount; @@ -351,7 +357,7 @@ VectorPath::AddPoint(const BPoint& point, return false; } -// AddPoint + bool VectorPath::AddPoint(BPoint point, int32 index) { @@ -377,12 +383,11 @@ VectorPath::AddPoint(BPoint point, int32 index) return false; } -// RemovePoint + bool VectorPath::RemovePoint(int32 index) { if (index >= 0 && index < fPointCount) { - if (index < fPointCount - 1) { // move points for (int32 i = index; i < fPointCount - 1; i++) { @@ -402,7 +407,7 @@ VectorPath::RemovePoint(int32 index) return false; } -// SetPoint + bool VectorPath::SetPoint(int32 index, BPoint point) { @@ -422,11 +427,10 @@ VectorPath::SetPoint(int32 index, BPoint point) return false; } -// SetPoint + bool -VectorPath::SetPoint(int32 index, BPoint point, - BPoint pointIn, BPoint pointOut, - bool connected) +VectorPath::SetPoint(int32 index, BPoint point, BPoint pointIn, BPoint pointOut, + bool connected) { if (index == fPointCount) index = 0; @@ -444,7 +448,7 @@ VectorPath::SetPoint(int32 index, BPoint point, return false; } -// SetPointIn + bool VectorPath::SetPointIn(int32 i, BPoint point) { @@ -459,8 +463,9 @@ VectorPath::SetPointIn(int32 i, BPoint point) BPoint v = fPath[i].point - fPath[i].point_in; float distIn = sqrtf(v.x * v.x + v.y * v.y); if (distIn > 0.0) { - float distOut = agg::calc_distance(fPath[i].point.x, fPath[i].point.y, - fPath[i].point_out.x, fPath[i].point_out.y); + float distOut = agg::calc_distance( + fPath[i].point.x, fPath[i].point.y, + fPath[i].point_out.x, fPath[i].point_out.y); float scale = (distIn + distOut) / distIn; v.x *= scale; v.y *= scale; @@ -476,7 +481,7 @@ VectorPath::SetPointIn(int32 i, BPoint point) return false; } -// SetPointOut + bool VectorPath::SetPointOut(int32 i, BPoint point, bool mirrorDist) { @@ -495,8 +500,9 @@ VectorPath::SetPointOut(int32 i, BPoint point, bool mirrorDist) BPoint v = fPath[i].point - fPath[i].point_out; float distOut = sqrtf(v.x * v.x + v.y * v.y); if (distOut > 0.0) { - float distIn = agg::calc_distance(fPath[i].point.x, fPath[i].point.y, - fPath[i].point_in.x, fPath[i].point_in.y); + float distIn = agg::calc_distance( + fPath[i].point.x, fPath[i].point.y, + fPath[i].point_in.x, fPath[i].point_in.y); float scale = (distIn + distOut) / distOut; v.x *= scale; v.y *= scale; @@ -512,7 +518,7 @@ VectorPath::SetPointOut(int32 i, BPoint point, bool mirrorDist) return false; } -// SetInOutConnected + bool VectorPath::SetInOutConnected(int32 index, bool connected) { @@ -521,12 +527,13 @@ VectorPath::SetInOutConnected(int32 index, bool connected) _NotifyPointChanged(index); return true; } - return false; + return false; } + // #pragma mark - -// GetPointAt + bool VectorPath::GetPointAt(int32 index, BPoint& point) const { @@ -539,7 +546,7 @@ VectorPath::GetPointAt(int32 index, BPoint& point) const return false; } -// GetPointInAt + bool VectorPath::GetPointInAt(int32 index, BPoint& point) const { @@ -552,7 +559,7 @@ VectorPath::GetPointInAt(int32 index, BPoint& point) const return false; } -// GetPointOutAt + bool VectorPath::GetPointOutAt(int32 index, BPoint& point) const { @@ -565,10 +572,10 @@ VectorPath::GetPointOutAt(int32 index, BPoint& point) const return false; } -// GetPointsAt + bool -VectorPath::GetPointsAt(int32 index, BPoint& point, - BPoint& pointIn, BPoint& pointOut, bool* connected) const +VectorPath::GetPointsAt(int32 index, BPoint& point, BPoint& pointIn, + BPoint& pointOut, bool* connected) const { if (index >= 0 && index < fPointCount) { point = fPath[index].point; @@ -583,23 +590,24 @@ VectorPath::GetPointsAt(int32 index, BPoint& point, return false; } -// CountPoints + int32 VectorPath::CountPoints() const { return fPointCount; } + // #pragma mark - + #ifdef ICON_O_MATIC -// distance_to_curve static float -distance_to_curve(const BPoint& p, const BPoint& a, const BPoint& aOut, const BPoint& bIn, const BPoint& b) +distance_to_curve(const BPoint& p, const BPoint& a, const BPoint& aOut, + const BPoint& bIn, const BPoint& b) { - agg::curve4_inc curve(a.x, a.y, aOut.x, aOut.y, - bIn.x, bIn.y, b.x, b.y); + agg::curve4_inc curve(a.x, a.y, aOut.x, aOut.y, bIn.x, bIn.y, b.x, b.y); float segDist = FLT_MAX; double x1, y1, x2, y2; @@ -615,25 +623,25 @@ distance_to_curve(const BPoint& p, const BPoint& a, const BPoint& aOut, const BP if (a > 0.0 && b > 0.0) { double c = agg::calc_distance(x1, y1, x2, y2); - double alpha = acos((b*b + c*c - a*a) / (2*b*c)); - double beta = acos((a*a + c*c - b*b) / (2*a*c)); - - if (alpha <= PI2 && beta <= PI2) { - currentDist = fabs(agg::calc_line_point_distance( - x1, y1, x2, y2, p.x, p.y)); + double alpha = acos((b * b + c * c - a * a) / (2 * b * c)); + double beta = acos((a * a + c * c - b * b) / (2 * a * c)); + + if (alpha <= M_PI_2 && beta <= M_PI_2) { + currentDist = fabs(agg::calc_line_point_distance(x1, y1, x2, y2, + p.x, p.y)); } } - if (currentDist < segDist) { + if (currentDist < segDist) segDist = currentDist; - } + x1 = x2; y1 = y2; } return segDist; } -// GetDistance + bool VectorPath::GetDistance(BPoint p, float* distance, int32* index) const { @@ -643,22 +651,17 @@ VectorPath::GetDistance(BPoint p, float* distance, int32* index) const *distance = FLT_MAX; for (int32 i = 0; i < fPointCount - 1; i++) { - float segDist = distance_to_curve(p, - fPath[i].point, - fPath[i].point_out, - fPath[i + 1].point_in, - fPath[i + 1].point); + float segDist = distance_to_curve(p, fPath[i].point, + fPath[i].point_out, fPath[i + 1].point_in, fPath[i + 1].point); if (segDist < *distance) { *distance = segDist; *index = i + 1; } } if (fClosed) { - float segDist = distance_to_curve(p, - fPath[fPointCount - 1].point, - fPath[fPointCount - 1].point_out, - fPath[0].point_in, - fPath[0].point); + float segDist = distance_to_curve(p, fPath[fPointCount - 1].point, + fPath[fPointCount - 1].point_out, fPath[0].point_in, + fPath[0].point); if (segDist < *distance) { *distance = segDist; *index = fPointCount; @@ -669,14 +672,13 @@ VectorPath::GetDistance(BPoint p, float* distance, int32* index) const return false; } -// FindBezierScale + bool VectorPath::FindBezierScale(int32 index, BPoint point, double* scale) const { if (index >= 0 && index < fPointCount && scale) { + int maxStep = 1000; - int maxStep = 1000; - double t = 0.0; double dt = 1.0 / maxStep; @@ -689,7 +691,7 @@ VectorPath::FindBezierScale(int32 index, BPoint point, double* scale) const GetPoint(index, t, curvePoint); double d = agg::calc_distance(curvePoint.x, curvePoint.y, - point.x, point.y); + point.x, point.y); if (d < min) { min = d; @@ -701,37 +703,32 @@ VectorPath::FindBezierScale(int32 index, BPoint point, double* scale) const return false; } -// GetPoint + bool VectorPath::GetPoint(int32 index, double t, BPoint& point) const { if (index >= 0 && index < fPointCount) { - double t1 = (1 - t) * (1 - t) * (1 - t); double t2 = (1 - t) * (1 - t) * t * 3; double t3 = (1 - t) * t * t * 3; double t4 = t * t * t; - + if (index < fPointCount - 1) { - point.x = fPath[index].point.x * t1 + - fPath[index].point_out.x * t2 + - fPath[index + 1].point_in.x * t3 + - fPath[index + 1].point.x * t4; - - point.y = fPath[index].point.y * t1 + - fPath[index].point_out.y * t2 + - fPath[index + 1].point_in.y * t3 + - fPath[index + 1].point.y * t4; + point.x = fPath[index].point.x * t1 + fPath[index].point_out.x * t2 + + fPath[index + 1].point_in.x * t3 + + fPath[index + 1].point.x * t4; + + point.y = fPath[index].point.y * t1 + fPath[index].point_out.y * t2 + + fPath[index + 1].point_in.y * t3 + + fPath[index + 1].point.y * t4; } else if (fClosed) { - point.x = fPath[fPointCount - 1].point.x * t1 + - fPath[fPointCount - 1].point_out.x * t2 + - fPath[0].point_in.x * t3 + - fPath[0].point.x * t4; - - point.y = fPath[fPointCount - 1].point.y * t1 + - fPath[fPointCount - 1].point_out.y * t2 + - fPath[0].point_in.y * t3 + - fPath[0].point.y * t4; + point.x = fPath[fPointCount - 1].point.x * t1 + + fPath[fPointCount - 1].point_out.x * t2 + + fPath[0].point_in.x * t3 + fPath[0].point.x * t4; + + point.y = fPath[fPointCount - 1].point.y * t1 + + fPath[fPointCount - 1].point_out.y * t2 + + fPath[0].point_in.y * t3 + fPath[0].point.y * t4; } return true; @@ -741,7 +738,7 @@ VectorPath::GetPoint(int32 index, double t, BPoint& point) const #endif // ICON_O_MATIC -// SetClosed + void VectorPath::SetClosed(bool closed) { @@ -752,7 +749,7 @@ VectorPath::SetClosed(bool closed) } } -// Bounds + BRect VectorPath::Bounds() const { @@ -762,7 +759,7 @@ VectorPath::Bounds() const return fCachedBounds; } -// Bounds + BRect VectorPath::_Bounds() const { @@ -770,7 +767,6 @@ VectorPath::_Bounds() const BRect b; if (get_path_storage(path, fPath, fPointCount, fClosed)) { - agg::conv_curve curve(path); uint32 pathID[1]; @@ -781,14 +777,15 @@ VectorPath::_Bounds() const b.Set(left, top, right, bottom); } else if (fPointCount == 1) { - b.Set(fPath[0].point.x, fPath[0].point.y, fPath[0].point.x, fPath[0].point.y); + b.Set(fPath[0].point.x, fPath[0].point.y, fPath[0].point.x, + fPath[0].point.y); } else { b.Set(0.0, 0.0, -1.0, -1.0); } return b; } -// ControlPointBounds + BRect VectorPath::ControlPointBounds() const { @@ -816,7 +813,7 @@ VectorPath::ControlPointBounds() const return BRect(0.0, 0.0, -1.0, -1.0); } -// Iterate + void VectorPath::Iterate(Iterator* iterator, float smoothScale) const { @@ -827,11 +824,11 @@ VectorPath::Iterate(Iterator* iterator, float smoothScale) const curve.approximation_scale(smoothScale); for (int32 i = 0; i < fPointCount - 1; i++) { -iterator->MoveTo(fPath[i].point); + iterator->MoveTo(fPath[i].point); curve.init(fPath[i].point.x, fPath[i].point.y, - fPath[i].point_out.x, fPath[i].point_out.y, - fPath[i + 1].point_in.x, fPath[i + 1].point_in.y, - fPath[i + 1].point.x, fPath[i + 1].point.y); + fPath[i].point_out.x, fPath[i].point_out.y, + fPath[i + 1].point_in.x, fPath[i + 1].point_in.y, + fPath[i + 1].point.x, fPath[i + 1].point.y); double x, y; unsigned cmd = curve.vertex(&x, &y); @@ -842,11 +839,13 @@ iterator->MoveTo(fPath[i].point); } } if (fClosed) { -iterator->MoveTo(fPath[fPointCount - 1].point); - curve.init(fPath[fPointCount - 1].point.x, fPath[fPointCount - 1].point.y, - fPath[fPointCount - 1].point_out.x, fPath[fPointCount - 1].point_out.y, - fPath[0].point_in.x, fPath[0].point_in.y, - fPath[0].point.x, fPath[0].point.y); + iterator->MoveTo(fPath[fPointCount - 1].point); + curve.init(fPath[fPointCount - 1].point.x, + fPath[fPointCount - 1].point.y, + fPath[fPointCount - 1].point_out.x, + fPath[fPointCount - 1].point_out.y, + fPath[0].point_in.x, fPath[0].point_in.y, + fPath[0].point.x, fPath[0].point.y); double x, y; unsigned cmd = curve.vertex(&x, &y); @@ -859,7 +858,7 @@ iterator->MoveTo(fPath[fPointCount - 1].point); } } -// CleanUp + void VectorPath::CleanUp() { @@ -880,9 +879,9 @@ VectorPath::CleanUp() for (int32 i = 0; i < fPointCount; i++) { // check for unnecessary, duplicate points if (i > 0) { - if (fPath[i - 1].point == fPath[i].point && - fPath[i - 1].point == fPath[i - 1].point_out && - fPath[i].point == fPath[i].point_in) { + if (fPath[i - 1].point == fPath[i].point + && fPath[i - 1].point == fPath[i - 1].point_out + && fPath[i].point == fPath[i].point_in) { // the previous point can be removed BPoint in = fPath[i - 1].point_in; if (RemovePoint(i - 1)) { @@ -894,18 +893,15 @@ VectorPath::CleanUp() } // re-establish connections of in-out control points if // they line up with the main control point - if (fPath[i].point_in == fPath[i].point_out || - fPath[i].point == fPath[i].point_out || - fPath[i].point == fPath[i].point_in || - (fabs(agg::calc_line_point_distance( - fPath[i].point_in.x, fPath[i].point_in.y, - fPath[i].point.x, fPath[i].point.y, - fPath[i].point_out.x, fPath[i].point_out.y)) < 0.01 && - fabs(agg::calc_line_point_distance( - fPath[i].point_out.x, fPath[i].point_out.y, - fPath[i].point.x, fPath[i].point.y, - fPath[i].point_in.x, fPath[i].point_in.y)) < 0.01)) { - + if (fPath[i].point_in == fPath[i].point_out + || fPath[i].point == fPath[i].point_out + || fPath[i].point == fPath[i].point_in + || (fabs(agg::calc_line_point_distance(fPath[i].point_in.x, + fPath[i].point_in.y, fPath[i].point.x, fPath[i].point.y, + fPath[i].point_out.x, fPath[i].point_out.y)) < 0.01 + && fabs(agg::calc_line_point_distance(fPath[i].point_out.x, + fPath[i].point_out.y, fPath[i].point.x, fPath[i].point.y, + fPath[i].point_in.x, fPath[i].point_in.y)) < 0.01)) { fPath[i].connected = true; notify = true; } @@ -915,17 +911,15 @@ VectorPath::CleanUp() _NotifyPathChanged(); } -// Reverse + void VectorPath::Reverse() { VectorPath temp(*this); int32 index = 0; for (int32 i = fPointCount - 1; i >= 0; i--) { - temp.SetPoint(index, fPath[i].point, - fPath[i].point_out, - fPath[i].point_in, - fPath[i].connected); + temp.SetPoint(index, fPath[i].point, fPath[i].point_out, + fPath[i].point_in, fPath[i].connected); index++; } *this = temp; @@ -933,7 +927,7 @@ VectorPath::Reverse() _NotifyPathReversed(); } -// ApplyTransform + void VectorPath::ApplyTransform(const Transformable& transform) { @@ -949,31 +943,31 @@ VectorPath::ApplyTransform(const Transformable& transform) _NotifyPathChanged(); } -// PrintToStream + void VectorPath::PrintToStream() const { for (int32 i = 0; i < fPointCount; i++) { printf("point %ld: (%f, %f) -> (%f, %f) -> (%f, %f) (%d)\n", i, - fPath[i].point_in.x, fPath[i].point_in.y, - fPath[i].point.x, fPath[i].point.y, - fPath[i].point_out.x, fPath[i].point_out.y, - fPath[i].connected); + fPath[i].point_in.x, fPath[i].point_in.y, + fPath[i].point.x, fPath[i].point.y, + fPath[i].point_out.x, fPath[i].point_out.y, fPath[i].connected); } } -// GetAGGPathStorage + bool VectorPath::GetAGGPathStorage(agg::path_storage& path) const { return get_path_storage(path, fPath, fPointCount, fClosed); } + // #pragma mark - + #ifdef ICON_O_MATIC -// AddListener bool VectorPath::AddListener(PathListener* listener) { @@ -982,21 +976,21 @@ VectorPath::AddListener(PathListener* listener) return false; } -// RemoveListener + bool VectorPath::RemoveListener(PathListener* listener) { return fListeners.RemoveItem((void*)listener); } -// CountListeners + int32 VectorPath::CountListeners() const { return fListeners.CountItems(); } -// ListenerAtFast + PathListener* VectorPath::ListenerAtFast(int32 index) const { @@ -1005,9 +999,10 @@ VectorPath::ListenerAtFast(int32 index) const #endif // ICON_O_MATIC + // #pragma mark - -// _SetPoint + void VectorPath::_SetPoint(int32 index, BPoint point) { @@ -1020,13 +1015,10 @@ VectorPath::_SetPoint(int32 index, BPoint point) fCachedBounds.Set(0.0, 0.0, -1.0, -1.0); } -// _SetPoint + void -VectorPath::_SetPoint(int32 index, - const BPoint& point, - const BPoint& pointIn, - const BPoint& pointOut, - bool connected) +VectorPath::_SetPoint(int32 index, const BPoint& point, const BPoint& pointIn, + const BPoint& pointOut, bool connected) { fPath[index].point = point; fPath[index].point_in = pointIn; @@ -1037,22 +1029,27 @@ VectorPath::_SetPoint(int32 index, fCachedBounds.Set(0.0, 0.0, -1.0, -1.0); } + // #pragma mark - -// _SetPointCount + bool VectorPath::_SetPointCount(int32 count) { // handle reallocation if we run out of room if (count >= fAllocCount) { fAllocCount = ((count) / ALLOC_CHUNKS + 1) * ALLOC_CHUNKS; - if (fPath) { + if (fPath) fPath = obj_renew(fPath, control_point, fAllocCount); - } else { + else fPath = obj_new(control_point, fAllocCount); + + if (fPath != NULL) { + memset(fPath + fPointCount, 0, + (fAllocCount - fPointCount) * sizeof(control_point)); } - memset(fPath + fPointCount, 0, (fAllocCount - fPointCount) * sizeof(control_point)); } + // update point count if (fPath) { fPointCount = count; @@ -1060,7 +1057,8 @@ VectorPath::_SetPointCount(int32 count) // reallocation might have failed fPointCount = 0; fAllocCount = 0; - fprintf(stderr, "VectorPath::_SetPointCount(%ld) - allocation failed!\n", count); + fprintf(stderr, "VectorPath::_SetPointCount(%ld) - allocation failed!\n", + count); } fCachedBounds.Set(0.0, 0.0, -1.0, -1.0); @@ -1068,11 +1066,12 @@ VectorPath::_SetPointCount(int32 count) return fPath != NULL; } + // #pragma mark - + #ifdef ICON_O_MATIC -// _NotifyPointAdded void VectorPath::_NotifyPointAdded(int32 index) const { @@ -1084,7 +1083,7 @@ VectorPath::_NotifyPointAdded(int32 index) const } } -// _NotifyPointChanged + void VectorPath::_NotifyPointChanged(int32 index) const { @@ -1096,7 +1095,7 @@ VectorPath::_NotifyPointChanged(int32 index) const } } -// _NotifyPointRemoved + void VectorPath::_NotifyPointRemoved(int32 index) const { @@ -1108,7 +1107,7 @@ VectorPath::_NotifyPointRemoved(int32 index) const } } -// _NotifyPathChanged + void VectorPath::_NotifyPathChanged() const { @@ -1120,7 +1119,7 @@ VectorPath::_NotifyPathChanged() const } } -// _NotifyClosedChanged + void VectorPath::_NotifyClosedChanged() const { @@ -1132,7 +1131,7 @@ VectorPath::_NotifyClosedChanged() const } } -// _NotifyPathReversed + void VectorPath::_NotifyPathReversed() const { diff --git a/src/libs/icon/transformable/Transformable.cpp b/src/libs/icon/transformable/Transformable.cpp index bcdd57fc30..a2c2cfec23 100644 --- a/src/libs/icon/transformable/Transformable.cpp +++ b/src/libs/icon/transformable/Transformable.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2006, Haiku. + * Copyright 2006-2009, Haiku. * Distributed under the terms of the MIT License. * * Authors: @@ -185,7 +185,7 @@ Transformable::Transform(BPoint* point) const double y = point->y; transform(&x, &y); - + point->x = x; point->y = y; } @@ -216,7 +216,7 @@ Transformable::InverseTransform(BPoint* point) const double y = point->y; inverse_transform(&x, &y); - + point->x = x; point->y = y; } @@ -235,13 +235,13 @@ inline float min4(float a, float b, float c, float d) { return min_c(a, min_c(b, min_c(c, d))); -} +} inline float max4(float a, float b, float c, float d) { return max_c(a, max_c(b, max_c(c, d))); -} +} // TransformBounds BRect @@ -252,12 +252,12 @@ Transformable::TransformBounds(BRect bounds) const BPoint rt(bounds.right, bounds.top); BPoint lb(bounds.left, bounds.bottom); BPoint rb(bounds.right, bounds.bottom); - + Transform(<); Transform(&rt); Transform(&lb); Transform(&rb); - + return BRect(floorf(min4(lt.x, rt.x, lb.x, rb.x)), floorf(min4(lt.y, rt.y, lb.y, rb.y)), ceilf(max4(lt.x, rt.x, lb.x, rb.x)), @@ -282,7 +282,7 @@ Transformable::RotateBy(BPoint origin, double degrees) { if (degrees != 0.0) { multiply(agg::trans_affine_translation(-origin.x, -origin.y)); - multiply(agg::trans_affine_rotation(degrees * (PI / 180.0))); + multiply(agg::trans_affine_rotation(degrees * (M_PI / 180.0))); multiply(agg::trans_affine_translation(origin.x, origin.y)); TransformationChanged(); } diff --git a/src/preferences/screensaver/ScreenCornerSelector.cpp b/src/preferences/screensaver/ScreenCornerSelector.cpp index c8a6fede54..0582172c6c 100644 --- a/src/preferences/screensaver/ScreenCornerSelector.cpp +++ b/src/preferences/screensaver/ScreenCornerSelector.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2003-2006, Haiku. + * Copyright 2003-2009, Haiku. * Distributed under the terms of the MIT License. * * Authors: @@ -28,7 +28,8 @@ static const float kStopSize = 15.0f; ScreenCornerSelector::ScreenCornerSelector(BRect frame, const char *name, BMessage* message, uint32 resizingMode) - : BControl(frame, name, NULL, message, resizingMode, B_WILL_DRAW | B_NAVIGABLE), + : BControl(frame, name, NULL, message, resizingMode, + B_WILL_DRAW | B_NAVIGABLE), fCurrentCorner(NO_CORNER), fPreviousCorner(-1) { @@ -47,7 +48,8 @@ ScreenCornerSelector::_MonitorFrame() const else if (height * kAspectRatio > width) height = width / kAspectRatio; - return BRect((Bounds().Width() - width) / 2, (Bounds().Height() - height) / 2, + return BRect((Bounds().Width() - width) / 2, + (Bounds().Height() - height) / 2, (Bounds().Width() + width) / 2, (Bounds().Height() + height) / 2); } @@ -68,7 +70,7 @@ ScreenCornerSelector::_CenterFrame(BRect innerFrame) const void -ScreenCornerSelector::Draw(BRect update) +ScreenCornerSelector::Draw(BRect update) { rgb_color darkColor = {160, 160, 160, 255}; rgb_color blackColor = {0, 0, 0, 255}; @@ -82,36 +84,39 @@ ScreenCornerSelector::Draw(BRect update) if (!_InnerFrame(outerRect).Contains(update)) { // frame & background - + // if the focus is changing, we don't redraw the whole view, but only // the part that's affected by the change if (!IsFocusChanging()) { SetHighColor(darkColor); - FillRoundRect(outerRect, kMonitorBorderSize * 3 / 2, kMonitorBorderSize * 3 / 2); + FillRoundRect(outerRect, kMonitorBorderSize * 3 / 2, + kMonitorBorderSize * 3 / 2); } - + if (IsFocus() && Window()->IsActive()) SetHighColor(ui_color(B_KEYBOARD_NAVIGATION_COLOR)); else SetHighColor(blackColor); - StrokeRoundRect(outerRect, kMonitorBorderSize * 3 / 2, kMonitorBorderSize * 3 / 2); - + + StrokeRoundRect(outerRect, kMonitorBorderSize * 3 / 2, + kMonitorBorderSize * 3 / 2); + if (!IsFocusChanging()) { SetHighColor(210, 210, 255); FillRoundRect(innerRect, kMonitorBorderSize, kMonitorBorderSize); } - + if (IsFocus() && Window()->IsActive()) SetHighColor(ui_color(B_KEYBOARD_NAVIGATION_COLOR)); else SetHighColor(blackColor); StrokeRoundRect(innerRect, kMonitorBorderSize, kMonitorBorderSize); - + if (IsFocusChanging()) return; - + // power light - + SetHighColor(redColor); BPoint powerPos(outerRect.left + kMonitorBorderSize * 2, outerRect.bottom - kMonitorBorderSize); @@ -175,7 +180,7 @@ ScreenCornerSelector::SetCorner(screen_corner corner) void -ScreenCornerSelector::_DrawStop(BRect innerFrame) +ScreenCornerSelector::_DrawStop(BRect innerFrame) { BRect centerRect = _CenterFrame(innerFrame); float size = kStopSize; @@ -188,13 +193,13 @@ ScreenCornerSelector::_DrawStop(BRect innerFrame) rect.left = centerRect.left + (centerRect.Width() - size) / 2; } rect.right = rect.left + size - 1; - rect.bottom = rect.top + size - 1; + rect.bottom = rect.top + size - 1; SetHighColor(255, 0, 0); SetPenSize(2); StrokeEllipse(rect); - size -= ceilf(sin(PI / 4) * size + 2); + size -= ceilf(sin(M_PI / 4) * size + 2); rect.InsetBy(size, size); StrokeLine(rect.RightTop(), rect.LeftBottom()); @@ -203,11 +208,13 @@ ScreenCornerSelector::_DrawStop(BRect innerFrame) void -ScreenCornerSelector::_DrawArrow(BRect innerFrame) +ScreenCornerSelector::_DrawArrow(BRect innerFrame) { float size = kArrowSize; - float sizeX = fCurrentCorner == UP_LEFT_CORNER || fCurrentCorner == DOWN_LEFT_CORNER ? size : -size; - float sizeY = fCurrentCorner == UP_LEFT_CORNER || fCurrentCorner == UP_RIGHT_CORNER ? size : -size; + float sizeX = fCurrentCorner == UP_LEFT_CORNER + || fCurrentCorner == DOWN_LEFT_CORNER ? size : -size; + float sizeY = fCurrentCorner == UP_LEFT_CORNER + || fCurrentCorner == UP_RIGHT_CORNER ? size : -size; innerFrame.InsetBy(2, 2); BPoint origin(sizeX < 0 ? innerFrame.right : innerFrame.left, @@ -220,7 +227,8 @@ ScreenCornerSelector::_DrawArrow(BRect innerFrame) screen_corner -ScreenCornerSelector::_ScreenCorner(BPoint point, screen_corner previousCorner) const +ScreenCornerSelector::_ScreenCorner(BPoint point, + screen_corner previousCorner) const { BRect innerFrame = _InnerFrame(_MonitorFrame()); @@ -240,7 +248,7 @@ ScreenCornerSelector::_ScreenCorner(BPoint point, screen_corner previousCorner) void -ScreenCornerSelector::MouseDown(BPoint where) +ScreenCornerSelector::MouseDown(BPoint where) { fPreviousCorner = Value(); @@ -250,14 +258,15 @@ ScreenCornerSelector::MouseDown(BPoint where) void -ScreenCornerSelector::MouseUp(BPoint where) +ScreenCornerSelector::MouseUp(BPoint where) { fPreviousCorner = -1; } void -ScreenCornerSelector::MouseMoved(BPoint where, uint32 transit, const BMessage* dragMessage) +ScreenCornerSelector::MouseMoved(BPoint where, uint32 transit, + const BMessage* dragMessage) { if (fPreviousCorner == -1) return; diff --git a/src/preferences/time/AnalogClock.cpp b/src/preferences/time/AnalogClock.cpp index 699973eb70..f4767881e0 100644 --- a/src/preferences/time/AnalogClock.cpp +++ b/src/preferences/time/AnalogClock.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2004-2006, Haiku, Inc. All Rights Reserved. + * Copyright 2004-2009, Haiku, Inc. All Rights Reserved. * Distributed under the terms of the MIT License. * * Authors: @@ -10,73 +10,70 @@ */ #include "AnalogClock.h" -#include "TimeMessages.h" + +#include +#include #include #include #include -#include -#include +#include "TimeMessages.h" + #define DRAG_DELTA_PHI 0.2 class OffscreenClock : public BView { - public: - OffscreenClock(BRect frame, const char *name); - ~OffscreenClock(); +public: + OffscreenClock(BRect frame, const char *name); + virtual ~OffscreenClock(); - void SetTime(int32 hour, int32 minute, int32 second); - void GetTime(int32 *hour, int32 *minute, int32 *second); - bool IsDirty() const { return fDirty; } - void DrawClock(); + void SetTime(int32 hour, int32 minute, int32 second); + void GetTime(int32 *hour, int32 *minute, int32 *second); + bool IsDirty() const { return fDirty; } + void DrawClock(); - bool InHourHand(BPoint point); - bool InMinuteHand(BPoint point); - - void SetHourHand(BPoint point); - void SetMinuteHand(BPoint point); + bool InHourHand(BPoint point); + bool InMinuteHand(BPoint point); - void SetHourDragging(bool val) { - fHourDragging = val; - fDirty = true; - } - void SetMinuteDragging(bool val) { - fMinuteDragging = val; - fDirty = true; - } - private: - float _GetPhi(BPoint point); - bool _InHand(BPoint point, int32 ticks, float radius); - void _DrawHands(float x, float y, float radius, - rgb_color hourHourColor, - rgb_color hourMinuteColor, - rgb_color secondsColor, - rgb_color knobColor); + void SetHourHand(BPoint point); + void SetMinuteHand(BPoint point); - int32 fHours; - int32 fMinutes; - int32 fSeconds; - bool fDirty; + void SetHourDragging(bool dragging); + void SetMinuteDragging(bool dragging); - float fCenterX; - float fCenterY; - float fRadius; +private: + float _GetPhi(BPoint point); + bool _InHand(BPoint point, int32 ticks, float radius); + void _DrawHands(float x, float y, float radius, + rgb_color hourHourColor, + rgb_color hourMinuteColor, + rgb_color secondsColor, rgb_color knobColor); - bool fHourDragging; - bool fMinuteDragging; + int32 fHours; + int32 fMinutes; + int32 fSeconds; + bool fDirty; + + float fCenterX; + float fCenterY; + float fRadius; + + bool fHourDragging; + bool fMinuteDragging; }; OffscreenClock::OffscreenClock(BRect frame, const char *name) - : BView(frame, name, B_FOLLOW_NONE, B_WILL_DRAW), - fHours(0), - fMinutes(0), - fSeconds(0), - fDirty(true), - fHourDragging(false), - fMinuteDragging(false) + : + BView(frame, name, B_FOLLOW_NONE, B_WILL_DRAW), + fHours(0), + fMinutes(0), + fSeconds(0), + fDirty(true), + fHourDragging(false), + fMinuteDragging(false) { SetFlags(Flags() | B_SUBPIXEL_PRECISE); @@ -131,9 +128,9 @@ OffscreenClock::DrawClock() SetHighColor(background); FillRect(bounds); - + bounds.Set(fCenterX - fRadius, fCenterY - fRadius, - fCenterX + fRadius, fCenterY + fRadius); + fCenterX + fRadius, fCenterY + fRadius); SetPenSize(2.0); @@ -148,7 +145,7 @@ OffscreenClock::DrawClock() SetLowColor(255, 255, 255); FillEllipse(bounds, B_SOLID_LOW); - + SetHighColor(tint_color(HighColor(), B_DARKEN_2_TINT)); // minutes @@ -157,10 +154,10 @@ OffscreenClock::DrawClock() for (int32 minute = 1; minute < 60; minute++) { if (minute % 5 == 0) continue; - float x1 = fCenterX + sinf(minute * PI / 30.0) * fRadius; - float y1 = fCenterY + cosf(minute * PI / 30.0) * fRadius; - float x2 = fCenterX + sinf(minute * PI / 30.0) * (fRadius * 0.95); - float y2 = fCenterY + cosf(minute * PI / 30.0) * (fRadius * 0.95); + float x1 = fCenterX + sinf(minute * M_PI / 30.0) * fRadius; + float y1 = fCenterY + cosf(minute * M_PI / 30.0) * fRadius; + float x2 = fCenterX + sinf(minute * M_PI / 30.0) * (fRadius * 0.95); + float y2 = fCenterY + cosf(minute * M_PI / 30.0) * (fRadius * 0.95); StrokeLine(BPoint(x1, y1), BPoint(x2, y2)); } @@ -170,10 +167,10 @@ OffscreenClock::DrawClock() SetPenSize(2.0); SetLineMode(B_ROUND_CAP, B_MITER_JOIN); for (int32 hour = 0; hour < 12; hour++) { - float x1 = fCenterX + sinf(hour * PI / 6.0) * fRadius; - float y1 = fCenterY + cosf(hour * PI / 6.0) * fRadius; - float x2 = fCenterX + sinf(hour * PI / 6.0) * (fRadius * 0.9); - float y2 = fCenterY + cosf(hour * PI / 6.0) * (fRadius * 0.9); + float x1 = fCenterX + sinf(hour * M_PI / 6.0) * fRadius; + float y1 = fCenterY + cosf(hour * M_PI / 6.0) * fRadius; + float x2 = fCenterX + sinf(hour * M_PI / 6.0) * (fRadius * 0.9); + float y2 = fCenterY + cosf(hour * M_PI / 6.0) * (fRadius * 0.9); StrokeLine(BPoint(x1, y1), BPoint(x2, y2)); } @@ -183,19 +180,21 @@ OffscreenClock::DrawClock() hourColor = (rgb_color){ 0, 0, 255, 255 }; else hourColor = tint_color(HighColor(), B_DARKEN_2_TINT); + rgb_color minuteColor; if (fMinuteDragging) minuteColor = (rgb_color){ 0, 0, 255, 255 }; else minuteColor = tint_color(HighColor(), B_DARKEN_2_TINT); + rgb_color secondsColor = (rgb_color){ 255, 0, 0, 255 }; rgb_color shadowColor = tint_color(LowColor(), (B_DARKEN_1_TINT + B_DARKEN_2_TINT) / 2); _DrawHands(fCenterX + 1.5, fCenterY + 1.5, fRadius, - shadowColor, shadowColor, shadowColor, shadowColor); + shadowColor, shadowColor, shadowColor, shadowColor); _DrawHands(fCenterX, fCenterY, fRadius, - hourColor, minuteColor, secondsColor, knobColor); + hourColor, minuteColor, secondsColor, knobColor); Sync(); @@ -231,7 +230,7 @@ OffscreenClock::SetHourHand(BPoint point) point.y -= fCenterY; float pointPhi = _GetPhi(point); - float hoursExact = 6.0 * pointPhi / PI; + float hoursExact = 6.0 * pointPhi / M_PI; if (fHours >= 12) fHours = 12; else @@ -249,50 +248,67 @@ OffscreenClock::SetMinuteHand(BPoint point) point.y -= fCenterY; float pointPhi = _GetPhi(point); - float minutesExact = 30.0 * pointPhi / PI; + float minutesExact = 30.0 * pointPhi / M_PI; fMinutes = int32(ceilf(minutesExact)); SetTime(fHours, fMinutes, fSeconds); } +void +OffscreenClock::SetHourDragging(bool dragging) +{ + fHourDragging = dragging; + fDirty = true; +} + + +void +OffscreenClock::SetMinuteDragging(bool dragging) +{ + fMinuteDragging = dragging; + fDirty = true; +} + + float OffscreenClock::_GetPhi(BPoint point) { if (point.x == 0 && point.y < 0) - return 2 * PI; + return 2 * M_PI; if (point.x == 0 && point.y > 0) - return PI; + return M_PI; if (point.y == 0 && point.x < 0) - return PI * 3 / 2; + return M_PI * 3 / 2; if (point.y == 0 && point.x > 0) - return PI / 2; + return M_PI / 2; float pointPhi = atanf(-1. * point.y / point.x); if (point.y < 0. && point.x > 0.) // right upper corner - pointPhi = PI / 2. - pointPhi; + pointPhi = M_PI / 2. - pointPhi; if (point.y > 0. && point.x > 0.) // right lower corner - pointPhi = PI / 2 - pointPhi; + pointPhi = M_PI / 2 - pointPhi; if (point.y > 0. && point.x < 0.) // left lower corner - pointPhi = (PI * 3. / 2. - pointPhi); + pointPhi = (M_PI * 3. / 2. - pointPhi); if (point.y < 0. && point.x < 0.) // left upper corner - pointPhi = 3. / 2. * PI - pointPhi; + pointPhi = 3. / 2. * M_PI - pointPhi; return pointPhi; } + bool OffscreenClock::_InHand(BPoint point, int32 ticks, float radius) { point.x -= fCenterX; point.y -= fCenterY; - + float pRadius = sqrt(pow(point.x, 2) + pow(point.y, 2)); if (radius < pRadius) return false; - + float pointPhi = _GetPhi(point); - float handPhi = PI / 30.0 * ticks; + float handPhi = M_PI / 30.0 * ticks; float delta = pointPhi - handPhi; if (fabs(delta) > DRAG_DELTA_PHI) return false; @@ -315,23 +331,23 @@ OffscreenClock::_DrawHands(float x, float y, float radius, SetHighColor(hourColor); SetPenSize(4.0); float hours = fHours + float(fMinutes) / 60.0; - offsetX = (radius * 0.7) * sinf((hours * PI) / 6.0); - offsetY = (radius * 0.7) * cosf((hours * PI) / 6.0); + offsetX = (radius * 0.7) * sinf((hours * M_PI) / 6.0); + offsetY = (radius * 0.7) * cosf((hours * M_PI) / 6.0); StrokeLine(BPoint(x, y), BPoint(x + offsetX, y - offsetY)); // calc, draw minute hand SetHighColor(minuteColor); SetPenSize(3.0); float minutes = fMinutes + float(fSeconds) / 60.0; - offsetX = (radius * 0.9) * sinf((minutes * PI) / 30.0); - offsetY = (radius * 0.9) * cosf((minutes * PI) / 30.0); + offsetX = (radius * 0.9) * sinf((minutes * M_PI) / 30.0); + offsetY = (radius * 0.9) * cosf((minutes * M_PI) / 30.0); StrokeLine(BPoint(x, y), BPoint(x + offsetX, y - offsetY)); // calc, draw second hand SetHighColor(secondsColor); SetPenSize(1.0); - offsetX = (radius * 0.95) * sinf((fSeconds * PI) / 30.0); - offsetY = (radius * 0.95) * cosf((fSeconds * PI) / 30.0); + offsetX = (radius * 0.95) * sinf((fSeconds * M_PI) / 30.0); + offsetY = (radius * 0.95) * cosf((fSeconds * M_PI) / 30.0); StrokeLine(BPoint(x, y), BPoint(x + offsetX, y - offsetY)); // draw the center knob @@ -344,7 +360,8 @@ OffscreenClock::_DrawHands(float x, float y, float radius, TAnalogClock::TAnalogClock(BRect frame, const char *name) - : BView(frame, name, B_FOLLOW_NONE, B_WILL_DRAW | B_DRAW_ON_CHILDREN), + : + BView(frame, name, B_FOLLOW_NONE, B_WILL_DRAW | B_DRAW_ON_CHILDREN), fBitmap(NULL), fClock(NULL), fDraggingHourHand(false), @@ -429,6 +446,7 @@ TAnalogClock::MouseDown(BPoint point) } } + void TAnalogClock::MouseUp(BPoint point) { @@ -452,7 +470,7 @@ TAnalogClock::MouseUp(BPoint point) void TAnalogClock::MouseMoved(BPoint point, uint32 transit, const BMessage *message) { - + if (fDraggingMinuteHand) fClock->SetMinuteHand(point); if (fDraggingHourHand) @@ -482,7 +500,7 @@ TAnalogClock::SetTime(int32 hour, int32 minute, int32 second) if (fClock) fClock->SetTime(hour, minute, second); - + Invalidate(); } diff --git a/src/servers/app/ServerFont.cpp b/src/servers/app/ServerFont.cpp index c2e6bb2e6d..0a1500f562 100644 --- a/src/servers/app/ServerFont.cpp +++ b/src/servers/app/ServerFont.cpp @@ -1,5 +1,5 @@ /* - * Copyright 2001-2008, Haiku. + * Copyright 2001-2009, Haiku. * Distributed under the terms of the MIT License. * * Authors: @@ -881,8 +881,8 @@ ServerFont::EmbeddedTransformation() const // TODO: cache this? Transformable transform; - transform.ShearBy(B_ORIGIN, (90.0 - fShear) * PI / 180.0, 0.0); - transform.RotateBy(B_ORIGIN, -fRotation * PI / 180.0); + transform.ShearBy(B_ORIGIN, (90.0 - fShear) * M_PI / 180.0, 0.0); + transform.RotateBy(B_ORIGIN, -fRotation * M_PI / 180.0); return transform; } diff --git a/src/servers/app/drawing/Painter/AGGTextRenderer.cpp b/src/servers/app/drawing/Painter/AGGTextRenderer.cpp index 5ed36f8be3..3341c2b0c7 100644 --- a/src/servers/app/drawing/Painter/AGGTextRenderer.cpp +++ b/src/servers/app/drawing/Painter/AGGTextRenderer.cpp @@ -76,9 +76,9 @@ AGGTextRenderer::SetFont(const ServerFont& font) // construct an embedded transformation (rotate & shear) fEmbeddedTransformation.Reset(); fEmbeddedTransformation.ShearBy(B_ORIGIN, - (90.0 - font.Shear()) * PI / 180.0, 0.0); + (90.0 - font.Shear()) * M_PI / 180.0, 0.0); fEmbeddedTransformation.RotateBy(B_ORIGIN, - -font.Rotation() * PI / 180.0); + -font.Rotation() * M_PI / 180.0); fContour.width(font.FalseBoldWidth() * 2.0); } diff --git a/src/servers/app/drawing/Painter/Painter.cpp b/src/servers/app/drawing/Painter/Painter.cpp index 0fd2801e3e..3a2588281d 100644 --- a/src/servers/app/drawing/Painter/Painter.cpp +++ b/src/servers/app/drawing/Painter/Painter.cpp @@ -81,6 +81,7 @@ using std::nothrow; #define CHECK_CLIPPING if (!fValidClipping) return BRect(0, 0, -1, -1); #define CHECK_CLIPPING_NO_RETURN if (!fValidClipping) return; + // constructor Painter::Painter() : @@ -1222,7 +1223,7 @@ Painter::DrawEllipse(BRect r, bool fill) const float yRadius = r.Height() / 2.0; BPoint center(r.left + xRadius, r.top + yRadius); - int32 divisions = (int32)((xRadius + yRadius + 2 * fPenSize) * PI / 2); + int32 divisions = (int32)((xRadius + yRadius + 2 * fPenSize) * M_PI / 2); if (divisions < 12) divisions = 12; if (divisions > 4096) @@ -1295,7 +1296,7 @@ Painter::FillEllipse(BRect r, const BGradient& gradient) const float yRadius = r.Height() / 2.0; BPoint center(r.left + xRadius, r.top + yRadius); - int32 divisions = (int32)((xRadius + yRadius + 2 * fPenSize) * PI / 2); + int32 divisions = (int32)((xRadius + yRadius + 2 * fPenSize) * M_PI / 2); if (divisions < 12) divisions = 12; if (divisions > 4096) @@ -1316,8 +1317,8 @@ Painter::StrokeArc(BPoint center, float xRadius, float yRadius, float angle, _Transform(¢er); - double angleRad = (angle * PI) / 180.0; - double spanRad = (span * PI) / 180.0; + double angleRad = (angle * M_PI) / 180.0; + double spanRad = (span * M_PI) / 180.0; agg::bezier_arc arc(center.x, center.y, xRadius, yRadius, -angleRad, -spanRad); @@ -1337,8 +1338,8 @@ Painter::FillArc(BPoint center, float xRadius, float yRadius, float angle, _Transform(¢er); - double angleRad = (angle * PI) / 180.0; - double spanRad = (span * PI) / 180.0; + double angleRad = (angle * M_PI) / 180.0; + double spanRad = (span * M_PI) / 180.0; agg::bezier_arc arc(center.x, center.y, xRadius, yRadius, -angleRad, -spanRad); @@ -1374,8 +1375,8 @@ Painter::FillArc(BPoint center, float xRadius, float yRadius, float angle, _Transform(¢er); - double angleRad = (angle * PI) / 180.0; - double spanRad = (span * PI) / 180.0; + double angleRad = (angle * M_PI) / 180.0; + double spanRad = (span * M_PI) / 180.0; agg::bezier_arc arc(center.x, center.y, xRadius, yRadius, -angleRad, -spanRad);