示例#1
0
void File_Browser::dirty()
{
    //DJV_DEBUG("File_Browser::dirty");

    Dialog::dirty();

    // Update tooltips.

    const List<Shortcut> & shortcut = File_Browser_Prefs::global()->shortcut();

    _value_widget->tooltip(tooltip_value);

    _up_widget->tooltip(String_Format(tooltip_up).
        arg(Shortcut::label(shortcut[File_Browser_Prefs::UP].value)));
    _prev_widget->tooltip(String_Format(tooltip_prev).
        arg(Shortcut::label(shortcut[File_Browser_Prefs::PREV].value)));
    _reload_widget->tooltip(String_Format(tooltip_reload).
        arg(Shortcut::label(shortcut[File_Browser_Prefs::RELOAD].value)));

    // General updates.

    if (visible() && shown())
    {
        directory_update();
    }

    menu_update();
}
示例#2
0
void quicktime_init() throw (Error)
{
    ++_ref;

    if (_ref > 1)
    {
        return;
    }

    //DJV_DEBUG("quicktime_init");

    qt::OSErr err = qt::noErr;

# if defined(DJV_WINDOWS)

    //DJV_DEBUG_PRINT("initialize QTML");

    err = qt::InitializeQTML(0); //qt::kInitializeQTMLNoSoundFlag);

    if (err != qt::noErr)
    {
        Image_Io_Base::throw_error(name, String_Format(error_init).arg(err));
    }

    _init_qtml = true;

# endif // DJV_WINDOWS

    //DJV_DEBUG_PRINT("get version");

    long version = 0;
    err = qt::Gestalt(qt::gestaltQuickTime, &version);

    if (err != qt::noErr)
    {
        Image_Io_Base::throw_error(name, String_Format(error_version).arg(err));
    }

    //DJV_DEBUG_PRINT("version = " << version);

    //DJV_DEBUG_PRINT("enter movies");

    err = qt::EnterMovies();

    if (err != qt::noErr)
    {
        Image_Io_Base::throw_error(name, String_Format(error_init).arg(err));
    }

    _enter_movies = true;
}
示例#3
0
文件: HTTPClient.c 项目: tindzk/Jivai
void HTTP_Client_GetResponse(String hostname, String path, unsigned short port, String *resp) {
	Socket socket = Socket_New(Socket_Protocol_TCP);

	SocketConnection conn = Socket_Connect(&socket, hostname, port);

	typedef void (^CleanupBlock)(void *, void *);

	CleanupBlock cleanup = ^(void *a, void *b) {
		SocketConnection_Close(a);
		Socket_Destroy(b);
	};

	String request = String_Format(
		$(
			"GET % HTTP/1.1\r\n"
			"Host: %\r\n"
			"Connection: Close\r\n"
			"\r\n"),
		path,
		hostname);

	try {
		SocketConnection_Write(&conn, request.buf, request.len);
	} clean finally {
		cleanup(&socket, &conn);
		String_Destroy(&request);
	} tryEnd;

	while (HTTP_Client_Receive(&conn, resp));
}
示例#4
0
文件: push.c 项目: Volkanite/Push
VOID CopyProgress( UINT64 TotalSize, UINT64 TotalTransferred )
{
    WCHAR progressText[260];

    String_Format(progressText, 260, L"%I64d / %I64d", TotalTransferred, TotalSize);
    SetWindowTextW(CpwTextBoxHandle, progressText);
}
示例#5
0
文件: push.c 项目: Volkanite/Push
void WriteConfig(wchar_t *Button, int Value, wchar_t* File)
{
    wchar_t buffer[20];

    String_Format(buffer, 20, L"0x%X", Value);
    Ini_WriteString(CONTROLLER_SECTION, Button, buffer, File);
}
示例#6
0
文件: Storage.c 项目: tindzk/podfm
def(String, BuildPath, String provider) {
	String res = String_Format($("%/%"), this->base, provider);

	if (!Path_Exists(res)) {
		Path_Create(res);
	}

	return res;
}
示例#7
0
void Image_Group::toolbar_update()
{
    // Update tooltips.

    const List<djv::Shortcut> & shortcuts =
        Shortcut_Prefs::global()->shortcuts();

    _display_profile_widget->tooltip(String_Format(tooltip_display_profile).
        arg(djv::Shortcut::label(
            shortcuts[Shortcut::IMAGE_DISPLAY_PROFILE].value)));
}
示例#8
0
文件: push.c 项目: Volkanite/Push
VOID Push_FormatTime( WCHAR* Buffer )
{
    __int64 rawtime;
    FILETIME Now;
    TIME_INFORMATION timeInfo;


    NtGetSystemTimeAsFileTime(&Now);
    rawtime = FileTimeToUnixTime(&Now);

    GetTimeUnits(&timeInfo, rawtime);
    String_Format(Buffer, 20, L"%i:%i:%i", timeInfo.tm_hour, timeInfo.tm_min, timeInfo.tm_sec);
}
示例#9
0
/* Adds all locales from the program's external libraries. */
static sdef(int, onLibrary, struct dl_phdr_info *info, __unused size_t size, void *data) {
	DynInstName(self) $this = (DynInstName(self)) (self *) data;

	RdString path = String_FromNul((char *) info->dlpi_name);
	path.len != 0 || ret(0);

	RdString ext      = Path_getFileExtension(path);
	RdString fileName = Path_getFileName(path);

	Logger_Debug(&this->logger, $("Found external library %."), fileName);

	if (!String_Equals(ext, $("dll"))) {
		Logger_Debug(&this->logger, $("Incompatible library extension."));
		return 0;
	}

	String realPath;
	if (Path_isLink(path)) {
		realPath = Path_followLink(path);
	} else {
		realPath = String_Clone(path);
	}

	RdString folderPath = Path_getFolderPath(realPath.rd);
	RdString context    = String_Slice(fileName, 0, -4);

	String lngpath = String_Format($("%Locale/"), folderPath);

	if (!Path_exists(lngpath.rd)) {
		Logger_Debug(&this->logger, $("External library % has no locales."),
			context);
		String_Destroy(&lngpath);
	} else {
		if (Locale_hasContext(Locale_GetInstance(), context)) {
			Logger_Error(&this->logger, $(
				"The locale context % was already registered. Possibly "
				"the program maintains a local copy of its external locales."),
				context);
		} else {
			Logger_Debug(&this->logger,
				$("Adding locale directory % (for external library %)."),
				lngpath.rd, context);

			Locale_addContext(Locale_GetInstance(), context, lngpath);
		}
	}

	String_Destroy(&realPath);

	return 0;
}
示例#10
0
void Window::frame_update()
{
    DJV_DEBUG(String_Format("Window::frame_update(%%)").arg(int64_t(this)));
    DJV_DEBUG_PRINT("frame = " << _frame);

    callbacks(false);

    _slider->set(_frame);

    _widget->set(_movie.image(_frame));
    _widget->redraw();

    callbacks(true);
}
示例#11
0
文件: Time.c 项目: tindzk/Jivai
sdef(String, Format, self time) {
	String hour   = Number_Format(time.hour,   2);
	String minute = Number_Format(time.minute, 2);
	String second = Number_Format(time.second, 2);

	String fmt = String_Format($("%:%:%"),
		hour.rd, minute.rd, second.rd);

	String_Destroy(&second);
	String_Destroy(&minute);
	String_Destroy(&hour);

	return fmt;
}
示例#12
0
String File_Util::label_size(uint64_t in)
{
    if (in > Memory::terabyte)
    {
        return String_Format("%%TB").arg(in /
            static_cast<double>(Memory::terabyte), 0, -2);
    }
    else if (in > Memory::gigabyte)
    {
        return String_Format("%%GB").arg(in /
            static_cast<double>(Memory::gigabyte), 0, -2);
    }
    else if (in > Memory::megabyte)
    {
        return String_Format("%%MB").arg(in /
            static_cast<double>(Memory::megabyte), 0, -2);
    }
    else
    {
        return String_Format("%%KB").arg(in /
            static_cast<double>(Memory::kilobyte), 0, -2);
    }
}
示例#13
0
文件: Downloader.c 项目: tindzk/podfm
static def(String, BuildPath, String prefix, ListingItem *item, String ext) {
	String title = scall(Sanitize, item->title);
	String path  = Storage_BuildPath(this->storage, this->providerId);

	String res = String_Format($("%/%%%.%"),
		path,
		prefix, (prefix.len > 0) ? $(" ") : $(""),
		title, ext);

	String_Destroy(&path);
	String_Destroy(&title);

	return res;
}
示例#14
0
Window::Window(const String & in) :
    _play(false),
    _frame(0),
    _idle_init(false),
    _idle_frame(0)
{
    DJV_DEBUG(String_Format("Window::Window(%%)").arg(int64_t(this)));

    // Initialize.

    try
    {
        _movie.init(in);
    }
    catch (Error in)
    {
        DJV_AUDIO_APP->error(in);
    }

    _widget = new Image_View;
    _play_widget = new Tool_Button("playback_forward");
    _play_widget->type(Tool_Button::TOGGLE);
    _slider = new Int_Slider;

    Layout_V * layout = new Layout_V(this);
    layout->margin(0);
    layout->spacing(0);
    layout->add(_widget);
    layout->stretch(_widget);
    Layout_H * layout_h = new Layout_H(layout);
    layout_h->margin(0);
    layout_h->add(_play_widget);
    layout_h->add(_slider);
    layout_h->stretch(_slider);

    _slider->range(0, static_cast<int>(_movie.info_time().list.size()) - 1);

    dirty();
    size(_movie.info().size + V2i(0, size_min().y));

    frame_update();
    play_update();

    _play_widget->signal.set(this, play_callback);
    _slider->signal.set(this, frame_callback);
    close_signal.set(this, close_callback);

    show();
}
示例#15
0
void Save::_open(const String & in, const Image_Io_Info & info) throw (Error)
{
    //DJV_DEBUG("Save::_open");
    //DJV_DEBUG_PRINT("in = " << in);

    _close();

    // Initialize libpng.

    _png = png_create_write_struct(
        PNG_LIBPNG_VER_STRING,
        &_png_error,
        djv_png_error,
        djv_png_warning);

    if (! _png)
    {
        throw Error(name(), _png_error.msg);
    }

    SNPRINTF(
        _png_error.msg,
        cstring_size,
        String(String_Format(error_open).arg(in)).c_str());

    // Open.

#   if defined(DJV_WINDOWS)

    //! \todo MinGW does not define fopen_s()?
    //::fopen_s(&_f, in.c_str(), "wb");
    _f = ::fopen(in.c_str(), "wb");

#   else

    _f = ::fopen(in.c_str(), "wb");

#   endif

    if (! _f)
    {
        throw_error_open(name(), in);
    }

    if (! png_open(_f, _png, &_png_info, info))
    {
        throw Error(name(), _png_error.msg);
    }
}
示例#16
0
void Window::play_update()
{
    DJV_DEBUG(String_Format("Window::play_update(%%)").arg(int64_t(this)));
    DJV_DEBUG_PRINT("play = " << _play);

    callbacks(false);

    _play_widget->set(_play);

    if (_play)
    {
        _audio = std::auto_ptr<Audio>(new Audio);

        try
        {
            _audio->init(_movie.info_audio(), &_audio_buffer);
        }
        catch (Error in)
        {
            _audio.reset();
            DJV_AUDIO_APP->error(in);
        }

        _idle_init = false;

        DJV_AUDIO_APP->idle_add(this);
    }
    else
    {
        _audio.reset();
        _audio_buffer.clear();

        DJV_AUDIO_APP->idle_del(this);
    }

    callbacks(true);
}
示例#17
0
int main(void) {
	Socket socket = Socket_New(Socket_Protocol_TCP);

	SocketConnection conn =
		Socket_Connect(&socket, $("www.kernel.org"), 80);

	String d1, d2;

	String_Print(
		d1 = String_Format(
			$("Connected to %:%\n\n"),
			d2 = NetworkAddress_ToString(conn.addr),
			Int16_ToString(conn.addr.port)));

	String_Destroy(&d2);
	String_Destroy(&d1);

	String request = $(
		"GET / HTTP/1.1\r\n"
		"Host: www.kernel.org\r\n"
		"Connection: Close\r\n"
		"\r\n");

	SocketConnection_Write(&conn, request.buf, request.len);

	String response = StackString(2048);

	response.len = SocketConnection_Read(&conn, response.buf, response.size);

	String_Print(response);

	SocketConnection_Close(&conn);

	Socket_Destroy(&socket);

	return ExitStatus_Success;
}
示例#18
0
文件: Client.c 项目: tindzk/Jivai
def(bool, IsConnected) {
	return !this->closed;
}

def(void, Reopen) {
	if (this->closed) {
		call(Open);
	}
}

static def(void, _CreateRequest, ref(RequestItem) request, String *res) {
	String fmt = String_Format($(
		"% % %\r\n"
		"Host: %\r\n"
		"Connection: Keep-Alive\r\n"),

		HTTP_Method_ToString(request.method),
		request.path.rd,
		HTTP_Version_ToString(request.version),
		request.host.rd);

	String_Append(res, fmt.rd);

	String_Destroy(&fmt);

	if (request.method == HTTP_Method_Post) {
		if (request.data == NULL) {
			String_Append(res, $("Content-Length: 0\r\n"));
		} else {
			String_Append(res,
				$("Content-Type: application/x-www-form-urlencoded\r\n"));
示例#19
0
Int Lexer_ParseZero(Lexer lexer, Bool isFirstContentOnLine)
{
	const Byte *src = lexer->src;
	const Byte *end = lexer->end;
	const Byte *start, *digitsEnd;
	Token token = lexer->token;
	Byte ch;
	UInt64 value;
	String suffix;

	START_TOKEN(src - 1);
	start = src - 1;

	if (src < end && ((ch = *src) == 'x' || ch == 'X')) {
		// Hexadecimal integer, or possibly a zero byte.
		src++;

		if (src >= end || !(((ch = *src) >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'))) {
			// Not an error; this is decimal zero, as a byte.
			lexer->src = src;
			if (!EnsureEndOfNumber(lexer)) {
				lexer->token->text = String_FormatString(IllegalNumericSuffixMessage, String_Format("x%c", ch));
				return END_TOKEN(TOKEN_ERROR);
			}
			END_TOKEN(TOKEN_INTEGER32);
			return ProcessIntegerValue(lexer, 0, ZeroString, LowercaseXString);
		}
		else {
			// This is a hexadecimal integer.
			lexer->src = src;
			if (!ParseHexadecimalInteger(lexer, &value)) {
				lexer->token->text = IllegalHexadecimalIntegerMessage;
				return END_TOKEN(TOKEN_ERROR);
			}
			digitsEnd = src = lexer->src;
			suffix = CollectAlphanumericSuffix(lexer);
			if (!EnsureEndOfNumber(lexer)) {
				lexer->token->text = String_FormatString(IllegalNumericSuffixMessage, String_Format("%c", *lexer->src));
				return END_TOKEN(TOKEN_ERROR);
			}
			END_TOKEN(TOKEN_INTEGER32);
			return ProcessIntegerValue(lexer, value, String_Create(start, digitsEnd - start), suffix);
		}
	}
	else {
		// Octal integer, or possibly a real value (if we find a '.').
		if (!ParseOctalInteger(lexer, &value)) {
			lexer->token->text = IllegalOctalIntegerMessage;
			return END_TOKEN(TOKEN_ERROR);
		}
		digitsEnd = src = lexer->src;
		if (src < lexer->end && *src == '.' && (src+1 >= lexer->end || src[1] != '.')) {
			// Found a '.' (and it's not part of a ".."), so rewind back and re-parse this as a real or float value.
			lexer->src = start;
			return Lexer_ParseReal(lexer, isFirstContentOnLine);
		}
		else {
			// Collected a whole octal value, so finish it.
			suffix = CollectAlphanumericSuffix(lexer);
			if (!EnsureEndOfNumber(lexer)) {
				lexer->token->text = String_FormatString(IllegalNumericSuffixMessage, String_Format("%c", *lexer->src));
				return END_TOKEN(TOKEN_ERROR);
			}
			END_TOKEN(TOKEN_INTEGER32);
			return ProcessIntegerValue(lexer, value, String_Create(start, digitsEnd - start), suffix);
		}
	}
}
示例#20
0
文件: string.cpp 项目: bitope/ags
// const char* (const char *texx, ...)
RuntimeScriptValue Sc_String_Format(const RuntimeScriptValue *params, int32_t param_count)
{
    API_SCALL_SCRIPT_SPRINTF(String_Format, 1);
    return RuntimeScriptValue().SetDynamicObject((void*)String_Format("%s", scsf_buffer), &myScriptStringImpl);
}
示例#21
0
void Scale_Op::render(const Image & in) throw (Error)
{
    //DJV_DEBUG("Scale_Op::render");
    //DJV_DEBUG_PRINT("in = " << in);
    //DJV_DEBUG_PRINT("size = " << _value.size);
    //DJV_DEBUG_PRINT("type = " << _value.type);

    // Initialize.

    Pixel_Data_Info info = in.info();

    begin();

    if (DEFAULT == _value.type)
    {
        _texture.init(
            info,
            filter_to_gl(_value.default_min),
            filter_to_gl(_value.default_mag));

        const State_Default state(_value);

        if (_state_default != state)
        {
            //DJV_DEBUG_PRINT("init");

            _render.shader.init(src_default);

            _state_default = state;
        }
    }
    else
    {
        _texture.init(info);

        _render.texture_tmp.init(
            Pixel_Data_Info(V2i(_value.size.x, in.h()), info.pixel));

        const State_Custom state(_value);

        if (_state_custom != state)
        {
            //DJV_DEBUG_PRINT("init");

            _render.offscreen.init();

            Pixel_Data contrib;
            contrib_fnc(
                in.w(),
                _value.size.x,
                _value.custom_min,
                _value.custom_mag,
                &contrib);
            _render.contrib_x.init(contrib);
            _render.shader_x.init(String_Format(src_custom).
                                  arg(contrib.h()).
                                  arg(src_x));

            contrib_fnc(
                in.h(),
                _value.size.y,
                _value.custom_min,
                _value.custom_mag,
                &contrib);
            _render.contrib_y.init(contrib);
            _render.shader_y.init(String_Format(src_custom).
                                  arg(contrib.h()).
                                  arg(src_y));

            _state_custom = state;
        }
    }

    // Render.

    if (DEFAULT == _value.type)
    {
        _render.shader.bind();
        const GLuint program = _render.shader.program();

        glUniform2f(glGetUniformLocation(program, "scale_input"),
            static_cast<GLfloat>(in.w()), static_cast<GLfloat>(in.h()));
        glUniform2f(glGetUniformLocation(program, "scale_output"),
            static_cast<GLfloat>(_value.size.x),
            static_cast<GLfloat>(_value.size.y));

        glActiveTexture(GL_TEXTURE0);
        glUniform1i(glGetUniformLocation(program, "texture"), 0);
        _texture.bind();
        _texture.copy(in);

        info = in.info();
        info.size = _value.size;
        Gl_Util::ortho(_value.size);
        glViewport(0, 0, _value.size.x, _value.size.y);
        glClear(GL_COLOR_BUFFER_BIT);
        Util::quad(info);
    }
    else
    {
        // Horizontal.

        _render.offscreen.bind();
        _render.offscreen.set(_render.texture_tmp);

        _render.shader_x.bind();

        glActiveTexture(GL_TEXTURE0);
        glUniform1i(
            glGetUniformLocation(_render.shader_x.program(), "texture"), 0);
        _texture.bind();
        _texture.copy(in);

        glActiveTexture(GL_TEXTURE1);
        glUniform1i(
            glGetUniformLocation(_render.shader_x.program(), "contrib"), 1);
        _render.contrib_x.bind();

        info = in.info();
        info.size.x = _value.size.x;
        Gl_Util::ortho(info.size);
        glViewport(0, 0, info.size.x, info.size.y);
        glClear(GL_COLOR_BUFFER_BIT);
        Util::quad(info);

        _render.offscreen.unbind();

        // Vertical.

        _render.shader_y.bind();

        glActiveTexture(GL_TEXTURE0);
        glUniform1i(
            glGetUniformLocation(_render.shader_y.program(), "texture"), 0);
        _render.texture_tmp.bind();

        glActiveTexture(GL_TEXTURE1);
        glUniform1i(
            glGetUniformLocation(_render.shader_y.program(), "contrib"), 1);
        _render.contrib_y.bind();

        Gl_Util::ortho(_value.size);
        glViewport(0, 0, _value.size.x, _value.size.y);
        glClear(GL_COLOR_BUFFER_BIT);
        Util::quad(Pixel_Data_Info(_value.size, in.pixel()));
    }

    end();
}
Glx_Context_Private::Glx_Context_Private() throw (Error) :
    _display      (0),
    _screen       (0),
    _visuals      (0),
    _visuals_count(0),
    _colormap     (0),
    _window       (0),
    _context      (0)
{
    //DJV_DEBUG("Glx_Context_Private::Glx_Context_Private");

    // Open the X display.

    _display = XOpenDisplay(NULL);

    if (! _display)
        throw Error(
            "Glx_Context_Private",
            "Cannot open X display");

    _screen = DefaultScreen(_display);

    // Choose a visual.

    XVisualInfo visualInfo;
    visualInfo.screen = _screen;
    visualInfo.depth  = 24;

    _visuals = XGetVisualInfo(
                   _display,
                   VisualScreenMask | VisualDepthMask,
                   &visualInfo,
                   &_visuals_count);

    if (! _visuals || ! _visuals_count)
        throw Error(
            "Glx_Context_Private",
            "No appropriate X visuals");

    // Create the color map.

    _colormap = XCreateColormap(
                    _display,
                    RootWindow(_display, _screen),
                    _visuals[0].visual,
                    AllocNone);

    if (! _colormap)
        throw Error(
            "Glx_Context_Private",
            "Cannot create X colormap");

    // Check for GLX support.

    if (! glXQueryExtension(_display, 0, 0))
        throw Error(
            "Glx_Context_Private",
            "No GLX extension");

    //! \todo Create a dummy window and rendering context for glewInit.

    XSetWindowAttributes winAttrib;
    winAttrib.colormap     = _colormap;
    winAttrib.border_pixel = 0;

    _window = XCreateWindow(
                  _display,
                  RootWindow(_display, _screen),
                  0, 0, 1, 1, 0,
                  visualInfo.depth,
                  InputOutput,
                  _visuals[0].visual,
                  CWColormap | CWBorderPixel,
                  &winAttrib);

    if (! _window)
        throw Error(
            "Glx_Context_Private",
            "Cannot create an X window");

    // Create the OpenGL context.

    _context = glXCreateContext(
                   _display,
                   &_visuals[0],
                   0,
                   True);

    if (! _context)
        throw Error(
            "Glx_Context_Private",
            "Cannot create OpenGL context");

    // Bind the context.

    bind();

    // Initialize GLEW.

    GLint glError = glewInit();

    if (glError != GLEW_OK)
        throw Error(
            "Glx_Context_Private",
            String_Format("Cannot initialize GLEW (#%%)").arg(glError));

    _vendor   = String((const char *)glGetString(GL_VENDOR));
    _renderer = String((const char *)glGetString(GL_RENDERER));
    _version  = String((const char *)glGetString(GL_VERSION));

    //DJV_DEBUG_PRINT("vendor string = " << _vendor);
    //DJV_DEBUG_PRINT("renderer string = " << _renderer);
    //DJV_DEBUG_PRINT("version string = " << _version);
    //DJV_DEBUG_PRINT("extensions = " <<
    //    (const char *)glGetString(GL_EXTENSIONS));
    //DJV_DEBUG_PRINT("glu version = " <<
    //    (const char *)gluGetString(GLU_VERSION));
    //DJV_DEBUG_PRINT("glu extensions = " <<
    //    (const char *)gluGetString(GLU_EXTENSIONS));

    if (! GL_EXT_framebuffer_object)
        throw Error(
            "Glx_Context_Private",
            "No OpenGL FBO support");
}
示例#23
0
文件: main.c 项目: seanofw/smile
static Bool PrintParseMessages(CommandLineArgs options, Parser parser)
{
	SmileList list;
	ParseMessage parseMessage;
	Bool hasErrors;
	Bool shouldPrint;
	const char *prefix;
	LexerPosition position;
	String message;

	hasErrors = False;

	for (list = parser->firstMessage; SMILE_KIND(list) != SMILE_KIND_NULL; list = LIST_REST(list)) {
		parseMessage = (ParseMessage)LIST_FIRST(list);

		shouldPrint = False;
	
		switch (parseMessage->messageKind) {
			case PARSEMESSAGE_INFO:
				if (options->verbose) {
					shouldPrint = True;
					prefix = "";
				}
				break;

			case PARSEMESSAGE_WARNING:
				if (options->warningsAsErrors) {
					shouldPrint = True;
					prefix = "warning: ";
					hasErrors = True;
				}
				else if (!options->quiet) {
					shouldPrint = True;
					prefix = "warning: ";
				}
				break;

			case PARSEMESSAGE_ERROR:
				shouldPrint = True;
				prefix = "";
				hasErrors = True;
				break;
		}
	
		if (!shouldPrint) continue;
	
		position = parseMessage->position;
		if (position->filename != NULL) {
			if (position->line > 0) {
				// Have a filename and a line number.
				message = String_Format("%S:%d: %s%S\r\n", position->filename, position->line, prefix, parseMessage->message);
			}
			else {
				// Have a filename but no line number.
				message = String_Format("%S: %s%S\r\n", position->filename, prefix, parseMessage->message);
			}
		}
		else {
			// Have no filename.
			message = String_Format("smile: %s%S\r\n", prefix, parseMessage->message);
		}
		
		fwrite(String_GetBytes(message), 1, String_Length(message), stderr);
	}

	return hasErrors;
}
示例#24
0
void Kernel::init(int size)
{
    _size = size;

    _src = String_Format(kernel_src).arg(_size);
}
示例#25
0
void Shader::init(const String & in) throw (Error)
{
    //DJV_DEBUG("Shader::init");
    //DJV_DEBUG_PRINT("in = " << in);

    GLint error = 0;

    del();

    DJV_DEBUG_GL(_vertex = glCreateShader(GL_VERTEX_SHADER));

    if (! _vertex)
    {
        throw Error("Vertex shader create.");
    }

    const String vertex_src =
        "void main(void)\n"
        "{\n"
        "  gl_FrontColor  = gl_Color;\n"
        "  gl_TexCoord[0] = gl_MultiTexCoord0;\n"
        "  gl_Position    = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
        "}\n";
    const char * vertex_sources [] = { vertex_src.c_str() };
    DJV_DEBUG_GL(glShaderSource(_vertex, 1, vertex_sources, 0));
    DJV_DEBUG_GL(glCompileShader(_vertex));
    char log [cstring_size] = "";
    glGetShaderInfoLog(_vertex, cstring_size, 0, log);
    //DJV_DEBUG_PRINT("log = " << log);
    glGetShaderiv(_vertex, GL_COMPILE_STATUS, &error);

    if (! error)
    {
        throw Error(
            String(String_Format("Vertex shader compile: %%").arg(log)));
    }

    DJV_DEBUG_GL(_fragment = glCreateShader(GL_FRAGMENT_SHADER));

    if (! _fragment)
    {
        throw Error("Fragment shader create.");
    }

    const char * fragment_sources [] = { in.c_str() };
    DJV_DEBUG_GL(glShaderSource(_fragment, 1, fragment_sources, 0));
    DJV_DEBUG_GL(glCompileShader(_fragment));
    glGetShaderInfoLog(_fragment, cstring_size, 0, log);
    //DJV_DEBUG_PRINT("log = " << log);
    glGetShaderiv(_fragment, GL_COMPILE_STATUS, &error);

    if (! error)
    {
        throw Error(
            String(String_Format("Fragment shader compile: %%").arg(log)));
    }

    DJV_DEBUG_GL(_program = glCreateProgram());
    DJV_DEBUG_GL(glAttachShader(_program, _vertex));
    DJV_DEBUG_GL(glAttachShader(_program, _fragment));
    DJV_DEBUG_GL(glLinkProgram(_program));
    glGetProgramInfoLog(_program, cstring_size, 0, log);
    //DJV_DEBUG_PRINT("log = " << log);
    glGetProgramiv(_program, GL_LINK_STATUS, &error);

    if (! error)
    {
        throw Error(String(String_Format("Shader compile: %%").arg(log)));
    }
}
示例#26
0
文件: Downloader.c 项目: tindzk/podfm
def(void, Get, String prefix, ListingItem *item, String url) {
	this->location.len = 0;

	HTTP_Client client;

	URL_Parts parts = URL_Parse(url);

	HTTP_Client_Init(&client, parts.host);

	HTTP_Client_Events events;
	events.onVersion = (HTTP_OnVersion) EmptyCallback();
	events.onHeader  = (HTTP_OnHeader) Callback(this, ref(OnHeader));

	HTTP_Client_SetEvents(&client, events);

	HTTP_Client_Request(&client,
		HTTP_Client_CreateRequest(
			parts.host,
			parts.path));

	Logger_Debug(this->logger, $("URL: %"), url);

	URL_Parts_Destroy(&parts);

	HTTP_Client_FetchResponse(&client);

	size_t cnt = 0;
	bool error = false;

	if (this->location.len > 0) {
		if (cnt > 3) {
			Logger_Error(this->logger, $("Redirection loop."));

			goto out;
		}

		cnt++;

		Logger_Debug(this->logger, $("Redirecting..."));

		call(Get, prefix, item, this->location);

		goto out;
	}

	String full = call(BuildPath, prefix, item,
		scall(GetMediaExtension, parts.path));

	Logger_Debug(this->logger, $("Destination: %"), full);

	File file;
	File_Open(&file, full,
		FileStatus_Create   |
		FileStatus_Truncate |
		FileStatus_WriteOnly);

	String_Destroy(&full);

	BufferedStream output;
	BufferedStream_Init(&output, File_AsStream(&file));
	BufferedStream_SetOutputBuffer(&output, 128 * 1024);

	u64 got   = 0;
	s64 total = HTTP_Client_GetLength(&client);

	size_t prevPercent = 100;

	String buf = String_New(HTTP_Client_ReadChunkSize);

	Terminal_ProgressBar pbar;
	Terminal_ProgressBar_Init(&pbar, &term);

	while (HTTP_Client_Read(&client, &buf)) {
		got += buf.len;

		try {
			BufferedStream_Write(&output, buf.buf, buf.len);
		} clean catch(File, WritingFailed) {
			error = true;
			excBreak;
		} finally {

		} tryEnd;

		size_t percent = (size_t) ((float) got / (float) total * 100);

		if (prevPercent != percent) {
			float gotmb   = (float) got   / 1024 / 1024;
			float totalmb = (float) total / 1024 / 1024;

			String strGot   = Float_ToString(gotmb,   0.01, '.');
			String strTotal = Float_ToString(totalmb, 0.01, '.');

			String msg = String_Format($("Received % MiB of % MiB"),
				strGot, strTotal);

			String_Destroy(&strTotal);
			String_Destroy(&strGot);

			Terminal_ProgressBar_Render(&pbar, percent, msg);

			String_Destroy(&msg);
		}

		prevPercent = percent;
	}

	Terminal_ProgressBar_Clear(&pbar);

	String_Destroy(&buf);

	if (error) {
		/* Don't flush when closing the file. */
		BufferedStream_Reset(&output);
	}

	BufferedStream_Close(&output);
	BufferedStream_Destroy(&output);

out:
	HTTP_Client_Destroy(&client);

	if (error) {
		throw(DownloadFailed);
	}
}
示例#27
0
文件: httpd.c 项目: tindzk/Jivai
def(void, OnRespond, bool persistent) {
	this->resp.len = 0;

	if (this->method == HTTP_Method_Get) {
		String_Append(&this->resp, $("Page requested via GET."));
	} else if (this->method == HTTP_Method_Post) {
		String_Append(&this->resp, $("Page requested via POST."));
	} else if (this->method == HTTP_Method_Head) {
		String_Append(&this->resp, $("Page requested via HEAD."));
	}

	if (this->method != HTTP_Method_Head) {
		String_Append(&this->resp,
			FmtString($(
				"<form action=\"/\" method=\"post\">"
				"<input type=\"text\" name=\"test\" /><br />"
				"<input type=\"text\" name=\"test2\" /><br />"
				"<input type=\"submit\" />"
				"</form>"
				"<br />"
				"You requested: %<br />"
				"test=%<br />"
				"test2=%<br />"
			),

			this->path.rd,
			this->paramTest.rd,
			this->paramTest2.rd));
	}

	String strLength = Integer_ToString(this->resp.len);

	String envelope = String_Format(
		$(
			"% 200 OK\r\n"
			"Content-Type: text/html; charset=utf-8\r\n"
			"%\r\n"
			"Content-Length: %\r\n"
			"\r\n"
		),

		HTTP_Version_ToString(this->version),

		persistent
			? $("Connection: Keep-Alive")
			: $("Connection: Close"),

		strLength.rd);

	String_Destroy(&strLength);

	SocketConnection_Write(this->conn, envelope.rd);

	size_t written = SocketConnection_Write(this->conn, this->resp.rd);
	String_Crop(&this->resp, written);

	SocketConnection_Flush(this->conn);

	String_Destroy(&envelope);

	this->paramTest.len  = 0;
	this->paramTest2.len = 0;

	/* You may want to change the value of this variable when the
	 * content length is unknown. If that's the case, you won't have
	 * no choice to indicate the end of the response but to close
	 * the connection.
	 */
	this->persistent = persistent;
}
示例#28
0
void Load::open(const File & in, Image_Io_Info & info) throw (Error)
{
    //DJV_DEBUG("Load::open");
    //DJV_DEBUG_PRINT("in = " << in);

    _close();

    // Open the file.

    CFStringRef cf_string_ref(File_Util::path_absolute(in));

    qt::QTNewMoviePropertyElement prop_list [10];
    qt::ItemCount prop_size = 0;

    prop_list[prop_size].propClass = qt::kQTPropertyClass_DataLocation;
    prop_list[prop_size].propID =
        qt::kQTDataLocationPropertyID_CFStringNativePath;
    //qt::kQTDataLocationPropertyID_CFStringPosixPath;
    prop_list[prop_size].propValueSize = sizeof(cf_string_ref.p);
    prop_list[prop_size].propValueAddress = (void *)&cf_string_ref.p;
    prop_list[prop_size].propStatus = 0;
    ++prop_size;

    qt::Boolean unresolved = true;
    prop_list[prop_size].propClass = qt::kQTPropertyClass_MovieInstantiation;
    prop_list[prop_size].propID =
        qt::kQTMovieInstantiationPropertyID_DontAskUnresolvedDataRefs;
    prop_list[prop_size].propValueSize = sizeof(unresolved);
    prop_list[prop_size].propValueAddress = &unresolved;
    prop_list[prop_size].propStatus = 0;
    ++prop_size;

    qt::Boolean active = true;
    prop_list[prop_size].propClass = qt::kQTPropertyClass_NewMovieProperty;
    prop_list[prop_size].propID = qt::kQTNewMoviePropertyID_Active;
    prop_list[prop_size].propValueSize = sizeof(active);
    prop_list[prop_size].propValueAddress = &active;
    prop_list[prop_size].propStatus = 0;
    ++prop_size;

    qt::Boolean no_interact = true;
    prop_list[prop_size].propClass = qt::kQTPropertyClass_NewMovieProperty;
    prop_list[prop_size].propID =
        qt::kQTNewMoviePropertyID_DontInteractWithUser;
    prop_list[prop_size].propValueSize = sizeof(no_interact);
    prop_list[prop_size].propValueAddress = &no_interact;
    prop_list[prop_size].propStatus = 0;
    ++prop_size;

    qt::QTVisualContextRef visual = 0;
    prop_list[prop_size].propClass = qt::kQTPropertyClass_Context;
    prop_list[prop_size].propID = qt::kQTContextPropertyID_VisualContext;
    prop_list[prop_size].propValueSize = sizeof(qt::QTVisualContextRef);
    prop_list[prop_size].propValueAddress = &visual;
    prop_list[prop_size].propStatus = 0;
    ++prop_size;

    qt::QTAudioContextRef audio = 0;
    prop_list[prop_size].propClass = qt::kQTPropertyClass_Context;
    prop_list[prop_size].propID = qt::kQTContextPropertyID_AudioContext;
    prop_list[prop_size].propValueSize = sizeof(qt::QTAudioContextRef);
    prop_list[prop_size].propValueAddress = &audio;
    prop_list[prop_size].propStatus = 0;
    ++prop_size;

    qt::OSErr err = qt::NewMovieFromProperties(
        prop_size,
        prop_list,
        0,
        0,
        &_movie);

    if (err != qt::noErr)
    {
        throw_error(name(), String_Format(error_open).arg(in).arg(err));
    }

    // Get the file information.

    _info.file_name = in;

    qt::Rect rect;
    qt::GetMovieBox(_movie, &rect);
    _info.size = V2i(rect.right - rect.left, rect.bottom - rect.top);
    _info.mirror.y = true;
    _info.pixel = Pixel::RGBA_U8;
    //_info.bgr = true;

    const qt::TimeScale time_scale = qt::GetMovieTimeScale(_movie);
    const qt::TimeValue time_duration = qt::GetMovieDuration(_movie);
    //const long frame_count = _frame_count(_movie);
    const qt::TimeValue frame_duration = _frame_duration(_movie);
    //const TimeValue frame_duration = time_duration / frame_count;
    _start_frame = _options.start_frame;

    //DJV_DEBUG_PRINT("time scale = " << static_cast<int>(time_scale));
    //DJV_DEBUG_PRINT("time duration = " << static_cast<int>(time_duration));
    //DJV_DEBUG_PRINT("frame count = " << static_cast<int>(frame_count));
    //DJV_DEBUG_PRINT("frame duration = " << static_cast<int>(frame_duration));
    //DJV_DEBUG_PRINT("start frame = " << _start_frame);

    _info.seq = Seq(
        _start_frame,
        frame_duration ?
        (_start_frame + (time_duration / frame_duration - 1)) :
        _start_frame,
        0,
        Speed(time_scale, frame_duration));

    //DJV_DEBUG_PRINT("time = " << _info.seq);

    info = _info;
    
    //! Allocate the temporary buffer.
    
    _tmp.set(_info);

    //! \todo Is this still necessary?

    unsigned long qt_format =
#   if defined(DJV_OSX)
        qt::k32ARGBPixelFormat;
#   else
        qt::k32RGBAPixelFormat;
#   endif

    err = qt::NewGWorldFromPtr(
        &_gworld,
        qt_format,
        &rect,
        0,
        0,
        0,
        (char *)_tmp.data(0, 0),
        _info.size.x * 4);

    if (err != qt::noErr)
    {
        throw_error(name(), String_Format(error_gworld).arg(in).arg(err));
    }

    qt::SetMovieGWorld(_movie, _gworld, 0);
}
示例#29
0
void Application::update()
{
    //DJV_DEBUG("Application::update");

    static Timer t;
    static double average = 0.0;
    static int accum = 0;

    t.check();
    const double fps = t.fps();
    t.start();

    if (fps < 1000.0)
    {
        average += fps;
        ++accum;
    }

    print(String_Format("FPS = %% (%%)").
          arg(fps).
          arg(average / static_cast<double>(accum)));

    try
    {
        //_image->load(_file.get(_file.seq().list[_frame]));

        _widget->set(_image0->p);
        _widget->redraw();

        int frame = _image1->frame + 1;

        if (_image_buf.size() > 1)
        {
            while (_image1->next != _image0 &&
                    frame < static_cast<int>(_file.seq().list.size()))
            {
                //DJV_DEBUG_PRINT("advance = " << frame);

                _image1 = _image1->next;
                _image1->p->load(_file.get(_file.seq().list[frame]));
                _image1->frame = frame;

                ++frame;
            }
        }
        else
        {
            if (frame < static_cast<int>(_file.seq().list.size()))
            {
                _image1 = _image1->next;
                _image1->p->load(_file.get(_file.seq().list[frame]));
                _image1->frame = frame;
            }
        }

        _image0 = _image0->next;
    }
    catch (Error error)
    {
        djv::Application::error(error);
    }

    ++_frame;

    if (_frame >= static_cast<int>(_file.seq().list.size()))
        //_frame = 0;
    {
        exit(EXIT_DEFAULT);
    }
}
示例#30
0
void Window::idle()
{
    DJV_DEBUG(String_Format("Window::idle(%%)").arg(int64_t(this)));

    if (_audio.get())
    {
        int size = _audio_buffer.size();
        DJV_DEBUG_PRINT("audio size = " << size);

        if (! size)
        {
            // Reset audio.

            _audio->stop();
            _audio_buffer.clear();
            _movie.audio_seek(_frame);
            _idle_init = false;
        }

        // Fill audio buffer.

        const int min = _audio_buffer.min();

        do
        {
            int16_t * p = _audio_buffer.push();

            if (! p)
            {
                break;
            }

            _movie.audio(
                p,
                _audio_buffer.chunk() / _movie.info_audio().channel);
        }
        while (++size < min)
            ;
    }

    if (! _idle_init)
    {
        DJV_DEBUG_PRINT("init");

        if (_audio.get())
        {
            _audio->start();
        }

        _idle_timer.start();
        _idle_frame = 0;
        _idle_init = true;
    }
    else
    {
        _idle_timer.check();
    }

    const double time = _audio.get() ? _audio->time() : _idle_timer.seconds();
    DJV_DEBUG_PRINT("time = " << time);

    if (time > 0.0)
    {
        const int64_t absolute_frame = Math::floor(time *
            Image_Speed::speed_to_float(_movie.info_time().speed));
        int inc = absolute_frame - _idle_frame;
        _idle_frame = absolute_frame;
        DJV_DEBUG_PRINT("absolute frame = " << absolute_frame);
        DJV_DEBUG_PRINT("inc = " << inc);

        if (inc)
        {
            _frame += inc;

            if (_frame >= static_cast<int>(_movie.info_time().list.size()))
            {
                _frame = 0;

                if (_audio.get())
                {
                    _audio->stop();
                }

                _audio_buffer.clear();

                _idle_init = false;
            }

            frame_update();
        }
    }
}