FlatCAMApp.py 289 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import sys
  9. import traceback
  10. import urllib.request, urllib.parse, urllib.error
  11. import getopt
  12. import os
  13. import random
  14. import logging
  15. import simplejson as json
  16. import re
  17. import os
  18. from stat import S_IREAD, S_IRGRP, S_IROTH
  19. import subprocess
  20. import tkinter as tk
  21. from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
  22. from PyQt5.QtCore import QSettings
  23. import time # Just used for debugging. Double check before removing.
  24. import urllib.request, urllib.parse, urllib.error
  25. import webbrowser
  26. from contextlib import contextmanager
  27. from xml.dom.minidom import parseString as parse_xml_string
  28. from copy import copy,deepcopy
  29. import numpy as np
  30. from datetime import datetime
  31. import gc
  32. ########################################
  33. ## Imports part of FlatCAM ##
  34. ########################################
  35. from ObjectCollection import *
  36. from FlatCAMObj import *
  37. from PlotCanvas import *
  38. from FlatCAMGUI import *
  39. from FlatCAMCommon import LoudDict
  40. from FlatCAMPostProc import load_postprocessors
  41. from FlatCAMEditor import FlatCAMGeoEditor, FlatCAMExcEditor
  42. from FlatCAMProcess import *
  43. from FlatCAMWorkerStack import WorkerStack
  44. from VisPyVisuals import Color
  45. from vispy.gloo.util import _screenshot
  46. from vispy.io import write_png
  47. from flatcamTools import *
  48. from multiprocessing import Pool
  49. import tclCommands
  50. # from ParseFont import *
  51. ########################################
  52. ## App ##
  53. ########################################
  54. class App(QtCore.QObject):
  55. """
  56. The main application class. The constructor starts the GUI.
  57. """
  58. # Get Cmd Line Options
  59. cmd_line_shellfile = ''
  60. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  61. try:
  62. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  63. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  64. except getopt.GetoptError:
  65. print(cmd_line_help)
  66. sys.exit(2)
  67. for opt, arg in cmd_line_options:
  68. if opt == '-h':
  69. print(cmd_line_help)
  70. sys.exit()
  71. elif opt == '--shellfile':
  72. cmd_line_shellfile = arg
  73. # Logging ##
  74. log = logging.getLogger('base')
  75. log.setLevel(logging.DEBUG)
  76. # log.setLevel(logging.WARNING)
  77. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  78. handler = logging.StreamHandler()
  79. handler.setFormatter(formatter)
  80. log.addHandler(handler)
  81. # Version
  82. version = 8.909
  83. version_date = "2019/02/16"
  84. beta = True
  85. # current date now
  86. date = str(datetime.today()).rpartition(' ')[0]
  87. # URL for update checks and statistics
  88. version_url = "http://flatcam.org/version"
  89. # App URL
  90. app_url = "http://flatcam.org"
  91. # Manual URL
  92. manual_url = "http://flatcam.org/manual/index.html"
  93. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  94. should_we_quit = True
  95. # this variable will hold the project status
  96. # if True it will mean that the project was modified and not saved
  97. should_we_save = False
  98. ##################
  99. ## Signals ##
  100. ##################
  101. # Inform the user
  102. # Handled by:
  103. # * App.info() --> Print on the status bar
  104. inform = QtCore.pyqtSignal(str)
  105. # General purpose background task
  106. worker_task = QtCore.pyqtSignal(dict)
  107. # File opened
  108. # Handled by:
  109. # * register_folder()
  110. # * register_recent()
  111. # Note: Setting the parameters to unicode does not seem
  112. # to have an effect. Then are received as Qstring
  113. # anyway.
  114. # File type and filename
  115. file_opened = QtCore.pyqtSignal(str, str)
  116. # File type and filename
  117. file_saved = QtCore.pyqtSignal(str, str)
  118. # Percentage of progress
  119. progress = QtCore.pyqtSignal(int)
  120. plots_updated = QtCore.pyqtSignal()
  121. # Emitted by new_object() and passes the new object as argument, plot flag.
  122. # on_object_created() adds the object to the collection, plots on appropriate flag
  123. # and emits new_object_available.
  124. object_created = QtCore.pyqtSignal(object, bool, bool)
  125. # Emitted when a object has been changed (like scaled, mirrored)
  126. object_changed = QtCore.pyqtSignal(object)
  127. # Emitted after object has been plotted.
  128. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  129. object_plotted = QtCore.pyqtSignal(object)
  130. # Emitted when a new object has been added to the collection
  131. # and is ready to be used.
  132. new_object_available = QtCore.pyqtSignal(object)
  133. message = QtCore.pyqtSignal(str, str, str)
  134. # Emmited when shell command is finished(one command only)
  135. shell_command_finished = QtCore.pyqtSignal(object)
  136. # Emitted when multiprocess pool has been recreated
  137. pool_recreated = QtCore.pyqtSignal(object)
  138. # Emitted when an unhandled exception happens
  139. # in the worker task.
  140. thread_exception = QtCore.pyqtSignal(object)
  141. def __init__(self, user_defaults=True, post_gui=None):
  142. """
  143. Starts the application.
  144. :return: app
  145. :rtype: App
  146. """
  147. App.log.info("FlatCAM Starting...")
  148. ###################
  149. ### OS-specific ###
  150. ###################
  151. # Folder for user settings.
  152. if sys.platform == 'win32':
  153. from win32com.shell import shell, shellcon
  154. if platform.architecture()[0] == '32bit':
  155. App.log.debug("Win32!")
  156. else:
  157. App.log.debug("Win64!")
  158. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
  159. '\FlatCAM'
  160. self.os = 'windows'
  161. else: # Linux/Unix/MacOS
  162. self.data_path = os.path.expanduser('~') + \
  163. '/.FlatCAM'
  164. self.os = 'unix'
  165. ###############################
  166. ### Setup folders and files ###
  167. ###############################
  168. if not os.path.exists(self.data_path):
  169. os.makedirs(self.data_path)
  170. App.log.debug('Created data folder: ' + self.data_path)
  171. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  172. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  173. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  174. if not os.path.exists(self.postprocessorpaths):
  175. os.makedirs(self.postprocessorpaths)
  176. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  177. # create current_defaults.FlatConfig file if there is none
  178. try:
  179. f = open(self.data_path + '/current_defaults.FlatConfig')
  180. f.close()
  181. except IOError:
  182. App.log.debug('Creating empty current_defaults.FlatConfig')
  183. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  184. json.dump({}, f)
  185. f.close()
  186. # create factory_defaults.FlatConfig file if there is none
  187. try:
  188. f = open(self.data_path + '/factory_defaults.FlatConfig')
  189. f.close()
  190. except IOError:
  191. App.log.debug('Creating empty factory_defaults.FlatConfig')
  192. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  193. json.dump({}, f)
  194. f.close()
  195. try:
  196. f = open(self.data_path + '/recent.json')
  197. f.close()
  198. except IOError:
  199. App.log.debug('Creating empty recent.json')
  200. f = open(self.data_path + '/recent.json', 'w')
  201. json.dump([], f)
  202. f.close()
  203. # Application directory. CHDIR to it. Otherwise, trying to load
  204. # GUI icons will fail as their path is relative.
  205. # This will fail under cx_freeze ...
  206. self.app_home = os.path.dirname(os.path.realpath(__file__))
  207. App.log.debug("Application path is " + self.app_home)
  208. App.log.debug("Started in " + os.getcwd())
  209. # cx_freeze workaround
  210. if os.path.isfile(self.app_home):
  211. self.app_home = os.path.dirname(self.app_home)
  212. os.chdir(self.app_home)
  213. # Create multiprocessing pool
  214. self.pool = Pool()
  215. # variable to store mouse coordinates
  216. self.mouse = [0, 0]
  217. ####################
  218. ## Initialize GUI ##
  219. ####################
  220. # FlatCAM colors used in plotting
  221. self.FC_light_green = '#BBF268BF'
  222. self.FC_dark_green = '#006E20BF'
  223. self.FC_light_blue = '#a5a5ffbf'
  224. self.FC_dark_blue = '#0000ffbf'
  225. QtCore.QObject.__init__(self)
  226. self.ui = FlatCAMGUI(self.version, self.beta, self)
  227. # self.connect(self.ui,
  228. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  229. # self.save_geometry) PyQt4
  230. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  231. self.ui.final_save.connect(self.final_save)
  232. ##############
  233. #### Data ####
  234. ##############
  235. self.recent = []
  236. self.clipboard = QtWidgets.QApplication.clipboard()
  237. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  238. self.project_filename = None
  239. self.toggle_units_ignore = False
  240. # self.defaults_form = PreferencesUI()
  241. self.general_defaults_form = GeneralPreferencesUI()
  242. self.gerber_defaults_form = GerberPreferencesUI()
  243. self.excellon_defaults_form = ExcellonPreferencesUI()
  244. self.geometry_defaults_form = GeometryPreferencesUI()
  245. self.cncjob_defaults_form = CNCJobPreferencesUI()
  246. self.tools_defaults_form = ToolsPreferencesUI()
  247. # when adding entries here read the comments in the method found bellow named:
  248. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  249. self.defaults_form_fields = {
  250. "units": self.general_defaults_form.general_app_group.units_radio,
  251. "global_shell_at_startup": self.general_defaults_form.general_app_group.shell_startup_cb,
  252. "global_version_check": self.general_defaults_form.general_app_group.version_check_cb,
  253. "global_send_stats": self.general_defaults_form.general_app_group.send_stats_cb,
  254. "global_project_at_startup": self.general_defaults_form.general_app_group.project_startup_cb,
  255. "global_project_autohide": self.general_defaults_form.general_app_group.project_autohide_cb,
  256. "global_gridx": self.general_defaults_form.general_gui_group.gridx_entry,
  257. "global_gridy": self.general_defaults_form.general_gui_group.gridy_entry,
  258. "global_snap_max": self.general_defaults_form.general_gui_group.snap_max_dist_entry,
  259. "global_plot_fill": self.general_defaults_form.general_gui_group.pf_color_entry,
  260. "global_plot_line": self.general_defaults_form.general_gui_group.pl_color_entry,
  261. "global_sel_fill": self.general_defaults_form.general_gui_group.sf_color_entry,
  262. "global_sel_line": self.general_defaults_form.general_gui_group.sl_color_entry,
  263. "global_alt_sel_fill": self.general_defaults_form.general_gui_group.alt_sf_color_entry,
  264. "global_alt_sel_line": self.general_defaults_form.general_gui_group.alt_sl_color_entry,
  265. "global_draw_color": self.general_defaults_form.general_gui_group.draw_color_entry,
  266. "global_sel_draw_color": self.general_defaults_form.general_gui_group.sel_draw_color_entry,
  267. "global_pan_button": self.general_defaults_form.general_app_group.pan_button_radio,
  268. "global_mselect_key": self.general_defaults_form.general_app_group.mselect_radio,
  269. # "global_pan_with_space_key": self.general_defaults_form.general_gui_group.pan_with_space_cb,
  270. "global_workspace": self.general_defaults_form.general_gui_group.workspace_cb,
  271. "global_workspaceT": self.general_defaults_form.general_gui_group.wk_cb,
  272. "gerber_plot": self.gerber_defaults_form.gerber_gen_group.plot_cb,
  273. "gerber_solid": self.gerber_defaults_form.gerber_gen_group.solid_cb,
  274. "gerber_multicolored": self.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  275. "gerber_circle_steps": self.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  276. "gerber_isotooldia": self.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  277. "gerber_isopasses": self.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  278. "gerber_isooverlap": self.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  279. "gerber_combine_passes": self.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  280. "gerber_milling_type": self.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  281. "gerber_noncoppermargin": self.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  282. "gerber_noncopperrounded": self.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  283. "gerber_bboxmargin": self.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  284. "gerber_bboxrounded": self.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  285. "excellon_plot": self.excellon_defaults_form.excellon_gen_group.plot_cb,
  286. "excellon_solid": self.excellon_defaults_form.excellon_gen_group.solid_cb,
  287. "excellon_format_upper_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  288. "excellon_format_lower_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  289. "excellon_format_upper_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  290. "excellon_format_lower_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  291. "excellon_zeros": self.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  292. "excellon_units": self.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  293. "excellon_optimization_type": self.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  294. "excellon_search_time": self.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  295. "excellon_offset": self.excellon_defaults_form.excellon_gen_group.offset_entry,
  296. "excellon_toolchangexy": self.excellon_defaults_form.excellon_gen_group.toolchangexy_entry,
  297. "excellon_startz": self.excellon_defaults_form.excellon_gen_group.estartz_entry,
  298. "excellon_endz": self.excellon_defaults_form.excellon_gen_group.eendz_entry,
  299. "excellon_feedrate_rapid": self.excellon_defaults_form.excellon_gen_group.feedrate_rapid_entry,
  300. "excellon_z_pdepth": self.excellon_defaults_form.excellon_gen_group.pdepth_entry,
  301. "excellon_feedrate_probe": self.excellon_defaults_form.excellon_gen_group.feedrate_probe_entry,
  302. "excellon_f_plunge": self.excellon_defaults_form.excellon_gen_group.fplunge_cb,
  303. "excellon_f_retract": self.excellon_defaults_form.excellon_gen_group.fretract_cb,
  304. "excellon_drillz": self.excellon_defaults_form.excellon_opt_group.cutz_entry,
  305. "excellon_travelz": self.excellon_defaults_form.excellon_opt_group.travelz_entry,
  306. "excellon_feedrate": self.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  307. "excellon_spindlespeed": self.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  308. "excellon_dwell": self.excellon_defaults_form.excellon_opt_group.dwell_cb,
  309. "excellon_dwelltime": self.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  310. "excellon_toolchange": self.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  311. "excellon_toolchangez": self.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  312. "excellon_ppname_e": self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  313. "excellon_tooldia": self.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  314. "excellon_slot_tooldia": self.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  315. "excellon_gcode_type": self.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  316. "excellon_exp_units": self.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  317. "excellon_exp_format": self.excellon_defaults_form.excellon_exp_group.format_radio,
  318. "excellon_exp_integer": self.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  319. "excellon_exp_decimals": self.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  320. "excellon_exp_zeros": self.excellon_defaults_form.excellon_exp_group.zeros_radio,
  321. "geometry_plot": self.geometry_defaults_form.geometry_gen_group.plot_cb,
  322. "geometry_cnctooldia": self.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  323. "geometry_circle_steps": self.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  324. "geometry_segx": self.geometry_defaults_form.geometry_gen_group.segx_entry,
  325. "geometry_segy": self.geometry_defaults_form.geometry_gen_group.segy_entry,
  326. "geometry_feedrate_rapid": self.geometry_defaults_form.geometry_gen_group.cncfeedrate_rapid_entry,
  327. "geometry_feedrate_probe": self.geometry_defaults_form.geometry_gen_group.feedrate_probe_entry,
  328. "geometry_z_pdepth": self.geometry_defaults_form.geometry_gen_group.pdepth_entry,
  329. "geometry_f_plunge": self.geometry_defaults_form.geometry_gen_group.fplunge_cb,
  330. "geometry_toolchangexy": self.geometry_defaults_form.geometry_gen_group.toolchangexy_entry,
  331. "geometry_startz": self.geometry_defaults_form.geometry_gen_group.gstartz_entry,
  332. "geometry_endz": self.geometry_defaults_form.geometry_gen_group.gendz_entry,
  333. "geometry_extracut": self.geometry_defaults_form.geometry_gen_group.extracut_cb,
  334. "geometry_cutz": self.geometry_defaults_form.geometry_opt_group.cutz_entry,
  335. "geometry_travelz": self.geometry_defaults_form.geometry_opt_group.travelz_entry,
  336. "geometry_feedrate": self.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  337. "geometry_feedrate_z": self.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  338. "geometry_spindlespeed": self.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  339. "geometry_dwell": self.geometry_defaults_form.geometry_opt_group.dwell_cb,
  340. "geometry_dwelltime": self.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  341. "geometry_ppname_g": self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  342. "geometry_toolchange": self.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  343. "geometry_toolchangez": self.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  344. "geometry_depthperpass": self.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  345. "geometry_multidepth": self.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  346. "cncjob_plot": self.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  347. "cncjob_plot_kind": self.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  348. "cncjob_tooldia": self.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  349. "cncjob_coords_decimals": self.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  350. "cncjob_fr_decimals": self.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  351. "cncjob_steps_per_circle": self.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  352. "cncjob_prepend": self.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  353. "cncjob_append": self.cncjob_defaults_form.cncjob_opt_group.append_text,
  354. "tools_ncctools": self.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  355. "tools_nccoverlap": self.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  356. "tools_nccmargin": self.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  357. "tools_nccmethod": self.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  358. "tools_nccconnect": self.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  359. "tools_ncccontour": self.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  360. "tools_nccrest": self.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  361. "tools_cutouttooldia": self.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  362. "tools_cutoutmargin": self.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  363. "tools_cutoutgapsize": self.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  364. "tools_gaps_rect": self.tools_defaults_form.tools_cutout_group.gaps_radio,
  365. "tools_gaps_ff": self.tools_defaults_form.tools_cutout_group.gaps_combo,
  366. "tools_painttooldia": self.tools_defaults_form.tools_paint_group.painttooldia_entry,
  367. "tools_paintoverlap": self.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  368. "tools_paintmargin": self.tools_defaults_form.tools_paint_group.paintmargin_entry,
  369. "tools_paintmethod": self.tools_defaults_form.tools_paint_group.paintmethod_combo,
  370. "tools_selectmethod": self.tools_defaults_form.tools_paint_group.selectmethod_combo,
  371. "tools_pathconnect": self.tools_defaults_form.tools_paint_group.pathconnect_cb,
  372. "tools_paintcontour": self.tools_defaults_form.tools_paint_group.contour_cb,
  373. "tools_2sided_mirror_axis": self.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  374. "tools_2sided_axis_loc": self.tools_defaults_form.tools_2sided_group.axis_location_radio,
  375. "tools_2sided_drilldia": self.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  376. "tools_film_type": self.tools_defaults_form.tools_film_group.film_type_radio,
  377. "tools_film_boundary": self.tools_defaults_form.tools_film_group.film_boundary_entry,
  378. "tools_film_scale": self.tools_defaults_form.tools_film_group.film_scale_entry,
  379. "tools_panelize_spacing_columns": self.tools_defaults_form.tools_panelize_group.pspacing_columns,
  380. "tools_panelize_spacing_rows": self.tools_defaults_form.tools_panelize_group.pspacing_rows,
  381. "tools_panelize_columns": self.tools_defaults_form.tools_panelize_group.pcolumns,
  382. "tools_panelize_rows": self.tools_defaults_form.tools_panelize_group.prows,
  383. "tools_panelize_constrain": self.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  384. "tools_panelize_constrainx": self.tools_defaults_form.tools_panelize_group.px_width_entry,
  385. "tools_panelize_constrainy": self.tools_defaults_form.tools_panelize_group.py_height_entry,
  386. "tools_calc_vshape_tip_dia": self.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  387. "tools_calc_vshape_tip_angle": self.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  388. "tools_calc_vshape_cut_z": self.tools_defaults_form.tools_calculators_group.cut_z_entry,
  389. "tools_calc_electro_length": self.tools_defaults_form.tools_calculators_group.pcblength_entry,
  390. "tools_calc_electro_width": self.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  391. "tools_calc_electro_cdensity": self.tools_defaults_form.tools_calculators_group.cdensity_entry,
  392. "tools_calc_electro_growth": self.tools_defaults_form.tools_calculators_group.growth_entry
  393. }
  394. # loads postprocessors
  395. self.postprocessors = load_postprocessors(self)
  396. for name in list(self.postprocessors.keys()):
  397. self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  398. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  399. if name == 'hpgl':
  400. continue
  401. self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  402. self.defaults = LoudDict()
  403. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  404. self.defaults.update({
  405. "global_serial": 0,
  406. "global_stats": {},
  407. "units": "IN",
  408. "global_version_check": True,
  409. "global_send_stats": True,
  410. "global_project_at_startup": False,
  411. "global_project_autohide": True,
  412. "global_gridx": 1.0,
  413. "global_gridy": 1.0,
  414. "global_snap_max": 0.05,
  415. "global_grid_context_menu": {
  416. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  417. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  418. },
  419. "global_plot_fill": '#BBF268BF',
  420. "global_plot_line": '#006E20BF',
  421. "global_sel_fill": '#a5a5ffbf',
  422. "global_sel_line": '#0000ffbf',
  423. "global_alt_sel_fill": '#BBF268BF',
  424. "global_alt_sel_line": '#006E20BF',
  425. "global_draw_color": '#FF0000',
  426. "global_sel_draw_color": '#0000FF',
  427. "global_pan_button": '2',
  428. "global_mselect_key": 'Control',
  429. # "global_pan_with_space_key": False,
  430. "global_workspace": False,
  431. "global_workspaceT": "A4P",
  432. "global_toolbar_view": 127,
  433. "global_background_timeout": 300000, # Default value is 5 minutes
  434. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  435. # (python trace only for unknown errors),
  436. # 1 = show trace(show trace allways),
  437. # 2 = (For the future).
  438. # Persistence
  439. "global_last_folder": None,
  440. "global_last_save_folder": None,
  441. # Default window geometry
  442. "global_def_win_x": 100,
  443. "global_def_win_y": 100,
  444. "global_def_win_w": 1024,
  445. "global_def_win_h": 650,
  446. # Constants...
  447. "global_defaults_save_period_ms": 20000, # Time between default saves.
  448. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  449. "global_shell_at_startup": False, # Show the shell at startup.
  450. "global_recent_limit": 10, # Max. items in recent list.
  451. "fit_key": 'V',
  452. "zoom_out_key": '-',
  453. "zoom_in_key": '=',
  454. "grid_toggle_key": 'G',
  455. "zoom_ratio": 1.5,
  456. "global_point_clipboard_format": "(%.4f, %.4f)",
  457. "global_zdownrate": None,
  458. "gerber_plot": True,
  459. "gerber_solid": True,
  460. "gerber_multicolored": False,
  461. "gerber_isotooldia": 0.016,
  462. "gerber_isopasses": 1,
  463. "gerber_isooverlap": 0.15,
  464. "gerber_combine_passes": False,
  465. "gerber_milling_type": "cl",
  466. "gerber_noncoppermargin": 0.1,
  467. "gerber_noncopperrounded": False,
  468. "gerber_bboxmargin": 0.1,
  469. "gerber_bboxrounded": False,
  470. "gerber_circle_steps": 64,
  471. "gerber_use_buffer_for_union": True,
  472. "excellon_plot": True,
  473. "excellon_solid": True,
  474. "excellon_format_upper_in": 2,
  475. "excellon_format_lower_in": 4,
  476. "excellon_format_upper_mm": 3,
  477. "excellon_format_lower_mm": 3,
  478. "excellon_zeros": "L",
  479. "excellon_units": "INCH",
  480. "excellon_optimization_type": 'B',
  481. "excellon_search_time": 3,
  482. "excellon_drillz": -0.1,
  483. "excellon_travelz": 0.1,
  484. "excellon_feedrate": 3.0,
  485. "excellon_feedrate_rapid": 3.0,
  486. "excellon_feedrate_probe": 3.0,
  487. "excellon_spindlespeed": None,
  488. "excellon_dwell": False,
  489. "excellon_dwelltime": 1,
  490. "excellon_toolchange": False,
  491. "excellon_toolchangez": 1.0,
  492. "excellon_toolchangexy": "0.0, 0.0",
  493. "excellon_tooldia": 0.016,
  494. "excellon_offset": 0.0,
  495. "excellon_slot_tooldia": 0.016,
  496. "excellon_startz": None,
  497. "excellon_endz": 2.0,
  498. "excellon_ppname_e": 'default',
  499. "excellon_z_pdepth": -0.02,
  500. "excellon_f_plunge": False,
  501. "excellon_f_retract": False,
  502. "excellon_gcode_type": "drills",
  503. "excellon_exp_units": 'INCH',
  504. "excellon_exp_format": 'ndec',
  505. "excellon_exp_integer": 2,
  506. "excellon_exp_decimals": 4,
  507. "excellon_exp_zeros": 'LZ',
  508. "geometry_plot": True,
  509. "geometry_segx": 0.0,
  510. "geometry_segy": 0.0,
  511. "geometry_cutz": -0.002,
  512. "geometry_travelz": 0.1,
  513. "geometry_toolchange": False,
  514. "geometry_toolchangez": 1.0,
  515. "geometry_toolchangexy": "0.0, 0.0",
  516. "geometry_startz": None,
  517. "geometry_endz": 2.0,
  518. "geometry_feedrate": 3.0,
  519. "geometry_feedrate_z": 3.0,
  520. "geometry_feedrate_rapid": 3.0,
  521. "geometry_feedrate_probe": 3.0,
  522. "geometry_cnctooldia": 0.016,
  523. "geometry_spindlespeed": None,
  524. "geometry_dwell": False,
  525. "geometry_dwelltime": 1,
  526. "geometry_ppname_g": 'default',
  527. "geometry_z_pdepth": -0.02,
  528. "geometry_f_plunge": False,
  529. "geometry_depthperpass": 0.002,
  530. "geometry_multidepth": False,
  531. "geometry_extracut": False,
  532. "geometry_circle_steps": 64,
  533. "cncjob_plot": True,
  534. "cncjob_plot_kind": 'all',
  535. "cncjob_tooldia": 0.0393701,
  536. "cncjob_coords_decimals": 4,
  537. "cncjob_fr_decimals": 2,
  538. "cncjob_prepend": "",
  539. "cncjob_append": "",
  540. "cncjob_steps_per_circle": 64,
  541. "tools_ncctools": "1.0, 0.5",
  542. "tools_nccoverlap": 0.4,
  543. "tools_nccmargin": 0.1,
  544. "tools_nccmethod": "seed",
  545. "tools_nccconnect": True,
  546. "tools_ncccontour": True,
  547. "tools_nccrest": False,
  548. "tools_cutouttooldia": 0.1,
  549. "tools_cutoutmargin": 0.1,
  550. "tools_cutoutgapsize": 0.15,
  551. "tools_gaps_rect": "4",
  552. "tools_gaps_ff": "8",
  553. "tools_painttooldia": 0.07,
  554. "tools_paintoverlap": 0.15,
  555. "tools_paintmargin": 0.0,
  556. "tools_paintmethod": "seed",
  557. "tools_selectmethod": "single",
  558. "tools_pathconnect": True,
  559. "tools_paintcontour": True,
  560. "tools_2sided_mirror_axis": "X",
  561. "tools_2sided_axis_loc": "point",
  562. "tools_2sided_drilldia": 1,
  563. "tools_film_type": 'neg',
  564. "tools_film_boundary": 1,
  565. "tools_film_scale": 0,
  566. "tools_panelize_spacing_columns": 0,
  567. "tools_panelize_spacing_rows": 0,
  568. "tools_panelize_columns": 1,
  569. "tools_panelize_rows": 1,
  570. "tools_panelize_constrain": False,
  571. "tools_panelize_constrainx": 0.0,
  572. "tools_panelize_constrainy": 0.0,
  573. "tools_calc_vshape_tip_dia": 0.007874,
  574. "tools_calc_vshape_tip_angle": 30,
  575. "tools_calc_vshape_cut_z": 0.000787,
  576. "tools_calc_electro_length": 10.0,
  577. "tools_calc_electro_width": 10.0,
  578. "tools_calc_electro_cdensity":13.0,
  579. "tools_calc_electro_growth": 10.0
  580. })
  581. ###############################
  582. ### Load defaults from file ###
  583. if user_defaults:
  584. self.load_defaults(filename='current_defaults')
  585. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  586. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  587. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  588. self.save_defaults(silent=True)
  589. self.propagate_defaults(silent=True)
  590. self.restore_main_win_geom()
  591. def auto_save_defaults():
  592. try:
  593. self.save_defaults(silent=True)
  594. self.propagate_defaults(silent=True)
  595. finally:
  596. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  597. # the following lines activates automatic defaults save
  598. # if user_defaults:
  599. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  600. # self.options_form = PreferencesUI()
  601. self.general_options_form = GeneralPreferencesUI()
  602. self.gerber_options_form = GerberPreferencesUI()
  603. self.excellon_options_form = ExcellonPreferencesUI()
  604. self.geometry_options_form = GeometryPreferencesUI()
  605. self.cncjob_options_form = CNCJobPreferencesUI()
  606. self.tools_options_form = ToolsPreferencesUI()
  607. self.options_form_fields = {
  608. "units": self.general_options_form.general_app_group.units_radio,
  609. "global_gridx": self.general_options_form.general_gui_group.gridx_entry,
  610. "global_gridy": self.general_options_form.general_gui_group.gridy_entry,
  611. "global_snap_max": self.general_options_form.general_gui_group.snap_max_dist_entry,
  612. "gerber_plot": self.gerber_options_form.gerber_gen_group.plot_cb,
  613. "gerber_solid": self.gerber_options_form.gerber_gen_group.solid_cb,
  614. "gerber_multicolored": self.gerber_options_form.gerber_gen_group.multicolored_cb,
  615. "gerber_isotooldia": self.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  616. "gerber_isopasses": self.gerber_options_form.gerber_opt_group.iso_width_entry,
  617. "gerber_isooverlap": self.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  618. "gerber_combine_passes": self.gerber_options_form.gerber_opt_group.combine_passes_cb,
  619. "gerber_noncoppermargin": self.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  620. "gerber_noncopperrounded": self.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  621. "gerber_bboxmargin": self.gerber_options_form.gerber_opt_group.bbmargin_entry,
  622. "gerber_bboxrounded": self.gerber_options_form.gerber_opt_group.bbrounded_cb,
  623. "excellon_plot": self.excellon_options_form.excellon_gen_group.plot_cb,
  624. "excellon_solid": self.excellon_options_form.excellon_gen_group.solid_cb,
  625. "excellon_format_upper_in": self.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  626. "excellon_format_lower_in": self.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  627. "excellon_format_upper_mm": self.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  628. "excellon_format_lower_mm": self.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  629. "excellon_zeros": self.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  630. "excellon_units": self.excellon_options_form.excellon_gen_group.excellon_units_radio,
  631. "excellon_optimization_type": self.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  632. "excellon_feedrate_rapid": self.excellon_options_form.excellon_gen_group.feedrate_rapid_entry,
  633. "excellon_toolchangexy": self.excellon_options_form.excellon_gen_group.toolchangexy_entry,
  634. "excellon_f_plunge": self.excellon_options_form.excellon_gen_group.fplunge_cb,
  635. "excellon_startz": self.excellon_options_form.excellon_gen_group.estartz_entry,
  636. "excellon_endz": self.excellon_options_form.excellon_gen_group.eendz_entry,
  637. "excellon_drillz": self.excellon_options_form.excellon_opt_group.cutz_entry,
  638. "excellon_travelz": self.excellon_options_form.excellon_opt_group.travelz_entry,
  639. "excellon_feedrate": self.excellon_options_form.excellon_opt_group.feedrate_entry,
  640. "excellon_spindlespeed": self.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  641. "excellon_dwell": self.excellon_options_form.excellon_opt_group.dwell_cb,
  642. "excellon_dwelltime": self.excellon_options_form.excellon_opt_group.dwelltime_entry,
  643. "excellon_toolchange": self.excellon_options_form.excellon_opt_group.toolchange_cb,
  644. "excellon_toolchangez": self.excellon_options_form.excellon_opt_group.toolchangez_entry,
  645. "excellon_tooldia": self.excellon_options_form.excellon_opt_group.tooldia_entry,
  646. "excellon_ppname_e": self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  647. "geometry_plot": self.geometry_options_form.geometry_gen_group.plot_cb,
  648. "geometry_cnctooldia": self.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  649. "geometry_segx": self.geometry_options_form.geometry_gen_group.segx_entry,
  650. "geometry_segy": self.geometry_options_form.geometry_gen_group.segy_entry,
  651. "geometry_feedrate_rapid": self.geometry_options_form.geometry_gen_group.cncfeedrate_rapid_entry,
  652. "geometry_f_plunge": self.geometry_options_form.geometry_gen_group.fplunge_cb,
  653. "geometry_toolchangexy": self.geometry_options_form.geometry_gen_group.toolchangexy_entry,
  654. "geometry_startz": self.geometry_options_form.geometry_gen_group.gstartz_entry,
  655. "geometry_endz": self.geometry_options_form.geometry_gen_group.gendz_entry,
  656. "geometry_extracut": self.geometry_options_form.geometry_gen_group.extracut_cb,
  657. "geometry_cutz": self.geometry_options_form.geometry_opt_group.cutz_entry,
  658. "geometry_travelz": self.geometry_options_form.geometry_opt_group.travelz_entry,
  659. "geometry_feedrate": self.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  660. "geometry_feedrate_z": self.geometry_options_form.geometry_opt_group.cncplunge_entry,
  661. "geometry_spindlespeed": self.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  662. "geometry_dwell": self.geometry_options_form.geometry_opt_group.dwell_cb,
  663. "geometry_dwelltime": self.geometry_options_form.geometry_opt_group.dwelltime_entry,
  664. "geometry_ppname_g": self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  665. "geometry_toolchange": self.geometry_options_form.geometry_opt_group.toolchange_cb,
  666. "geometry_toolchangez": self.geometry_options_form.geometry_opt_group.toolchangez_entry,
  667. "geometry_depthperpass": self.geometry_options_form.geometry_opt_group.depthperpass_entry,
  668. "geometry_multidepth": self.geometry_options_form.geometry_opt_group.multidepth_cb,
  669. "cncjob_plot": self.cncjob_options_form.cncjob_gen_group.plot_cb,
  670. "cncjob_tooldia": self.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  671. "cncjob_prepend": self.cncjob_options_form.cncjob_opt_group.prepend_text,
  672. "cncjob_append": self.cncjob_options_form.cncjob_opt_group.append_text,
  673. "tools_ncctools": self.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  674. "tools_nccoverlap": self.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  675. "tools_nccmargin": self.tools_options_form.tools_ncc_group.ncc_margin_entry,
  676. "tools_cutouttooldia": self.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  677. "tools_cutoutmargin": self.tools_options_form.tools_cutout_group.cutout_margin_entry,
  678. "tools_cutoutgapsize": self.tools_options_form.tools_cutout_group.cutout_gap_entry,
  679. "tools_gaps_rect": self.tools_options_form.tools_cutout_group.gaps_radio,
  680. "tools_gaps_ff": self.tools_options_form.tools_cutout_group.gaps_combo,
  681. "tools_painttooldia": self.tools_options_form.tools_paint_group.painttooldia_entry,
  682. "tools_paintoverlap": self.tools_options_form.tools_paint_group.paintoverlap_entry,
  683. "tools_paintmargin": self.tools_options_form.tools_paint_group.paintmargin_entry,
  684. "tools_paintmethod": self.tools_options_form.tools_paint_group.paintmethod_combo,
  685. "tools_selectmethod": self.tools_options_form.tools_paint_group.selectmethod_combo,
  686. "tools_pathconnect": self.tools_options_form.tools_paint_group.pathconnect_cb,
  687. "tools_paintcontour": self.tools_options_form.tools_paint_group.contour_cb,
  688. "tools_2sided_mirror_axis": self.tools_options_form.tools_2sided_group.mirror_axis_radio,
  689. "tools_2sided_axis_loc": self.tools_options_form.tools_2sided_group.axis_location_radio,
  690. "tools_2sided_drilldia": self.tools_options_form.tools_2sided_group.drill_dia_entry,
  691. "tools_film_type": self.tools_options_form.tools_film_group.film_type_radio,
  692. "tools_film_boundary": self.tools_options_form.tools_film_group.film_boundary_entry,
  693. "tools_film_scale": self.tools_options_form.tools_film_group.film_scale_entry,
  694. "tools_panelize_spacing_columns": self.tools_options_form.tools_panelize_group.pspacing_columns,
  695. "tools_panelize_spacing_rows": self.tools_options_form.tools_panelize_group.pspacing_rows,
  696. "tools_panelize_columns": self.tools_options_form.tools_panelize_group.pcolumns,
  697. "tools_panelize_rows": self.tools_options_form.tools_panelize_group.prows,
  698. "tools_panelize_constrain": self.tools_options_form.tools_panelize_group.pconstrain_cb,
  699. "tools_panelize_constrainx": self.tools_options_form.tools_panelize_group.px_width_entry,
  700. "tools_panelize_constrainy": self.tools_options_form.tools_panelize_group.py_height_entry
  701. }
  702. for name in list(self.postprocessors.keys()):
  703. self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  704. self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  705. self.options = LoudDict()
  706. self.options.set_change_callback(self.on_options_dict_change)
  707. self.options.update({
  708. "units": "IN",
  709. "global_gridx": 1.0,
  710. "global_gridy": 1.0,
  711. "global_snap_max": 0.05,
  712. "global_background_timeout": 300000, # Default value is 5 minutes
  713. "global_verbose_error_level": 0, # Shell verbosity:
  714. # 0 = default(python trace only for unknown errors),
  715. # 1 = show trace(show trace allways), 2 = (For the future).
  716. "gerber_plot": True,
  717. "gerber_solid": True,
  718. "gerber_multicolored": False,
  719. "gerber_isotooldia": 0.016,
  720. "gerber_isopasses": 1,
  721. "gerber_isooverlap": 0.15,
  722. "gerber_combine_passes": True,
  723. "gerber_noncoppermargin": 0.0,
  724. "gerber_noncopperrounded": False,
  725. "gerber_bboxmargin": 0.0,
  726. "gerber_bboxrounded": False,
  727. "excellon_plot": True,
  728. "excellon_solid": False,
  729. "excellon_format_upper_in": 2,
  730. "excellon_format_lower_in": 4,
  731. "excellon_format_upper_mm": 3,
  732. "excellon_format_lower_mm": 3,
  733. "excellon_units": 'INCH',
  734. "excellon_optimization_type": 'B',
  735. "excellon_search_time": 3,
  736. "excellon_zeros": "L",
  737. "excellon_drillz": -0.1,
  738. "excellon_travelz": 0.1,
  739. "excellon_feedrate": 3.0,
  740. "excellon_feedrate_rapid": 3.0,
  741. "excellon_spindlespeed": None,
  742. "excellon_dwell": True,
  743. "excellon_dwelltime": 1000,
  744. "excellon_toolchange": False,
  745. "excellon_toolchangez": 1.0,
  746. "excellon_toolchangexy": "0.0, 0.0",
  747. "excellon_tooldia": 0.016,
  748. "excellon_ppname_e": 'default',
  749. "excellon_f_plunge": False,
  750. "excellon_startz": None,
  751. "excellon_endz": 2.0,
  752. "geometry_plot": True,
  753. "geometry_segx": 0.0,
  754. "geometry_segy": 0.0,
  755. "geometry_cutz": -0.002,
  756. "geometry_travelz": 0.1,
  757. "geometry_feedrate": 3.0,
  758. "geometry_feedrate_z": 3.0,
  759. "geometry_feedrate_rapid": 3.0,
  760. "geometry_spindlespeed": None,
  761. "geometry_dwell": True,
  762. "geometry_dwelltime": 1000,
  763. "geometry_cnctooldia": 0.016,
  764. "geometry_toolchange": False,
  765. "geometry_toolchangez": 2.0,
  766. "geometry_toolchangexy": "0.0, 0.0",
  767. "geometry_startz": None,
  768. "geometry_endz": 2.0,
  769. "geometry_ppname_g": "default",
  770. "geometry_f_plunge": False,
  771. "geometry_depthperpass": 0.002,
  772. "geometry_multidepth": False,
  773. "geometry_extracut": False,
  774. "cncjob_plot": True,
  775. "cncjob_tooldia": 0.016,
  776. "cncjob_prepend": "",
  777. "cncjob_append": "",
  778. "tools_ncctools": "1.0, 0.5",
  779. "tools_nccoverlap": 0.4,
  780. "tools_nccmargin": 1,
  781. "tools_cutouttooldia": 0.07,
  782. "tools_cutoutmargin": 0.1,
  783. "tools_cutoutgapsize": 0.15,
  784. "tools_gaps_rect": "4",
  785. "tools_gaps_ff": "8",
  786. "tools_painttooldia": 0.07,
  787. "tools_paintoverlap": 0.15,
  788. "tools_paintmargin": 0.0,
  789. "tools_paintmethod": "seed",
  790. "tools_selectmethod": "single",
  791. "tools_pathconnect": True,
  792. "tools_paintcontour": True,
  793. "tools_2sided_mirror_axis": "X",
  794. "tools_2sided_axis_loc": 'point',
  795. "tools_2sided_drilldia": 1,
  796. "tools_film_type": 'neg',
  797. "tools_film_boundary": 1,
  798. "tools_film_scale": 0,
  799. "tools_panelize_spacing_columns": 0,
  800. "tools_panelize_spacing_rows": 0,
  801. "tools_panelize_columns": 1,
  802. "tools_panelize_rows": 1,
  803. "tools_panelize_constrain": False,
  804. "tools_panelize_constrainx": 0.0,
  805. "tools_panelize_constrainy": 0.0
  806. })
  807. self.options.update(self.defaults) # Copy app defaults to project options
  808. self.gen_form = None
  809. self.ger_form = None
  810. self.exc_form = None
  811. self.geo_form = None
  812. self.cnc_form = None
  813. self.tools_form = None
  814. self.on_options_combo_change(0) # Will show the initial form
  815. ### Define OBJECT COLLECTION ###
  816. self.collection = ObjectCollection(self)
  817. self.ui.project_tab_layout.addWidget(self.collection.view)
  818. ###
  819. self.log.debug("Finished creating Object Collection.")
  820. ### Initialize the color box's color in Preferences -> Global -> Color
  821. # Init Plot Colors
  822. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  823. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  824. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  825. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  826. int(self.defaults['global_plot_fill'][7:9], 16))
  827. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  828. int(self.defaults['global_plot_fill'][7:9], 16))
  829. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  830. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  831. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  832. # Init Left-Right Selection colors
  833. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  834. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  835. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  836. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  837. int(self.defaults['global_sel_fill'][7:9], 16))
  838. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  839. int(self.defaults['global_sel_fill'][7:9], 16))
  840. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  841. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  842. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  843. # Init Right-Left Selection colors
  844. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(self.defaults['global_alt_sel_fill'])
  845. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  846. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  847. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  848. int(self.defaults['global_sel_fill'][7:9], 16))
  849. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  850. int(self.defaults['global_sel_fill'][7:9], 16))
  851. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(self.defaults['global_alt_sel_line'])
  852. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  853. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  854. # Init Draw color and Selection Draw Color
  855. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(self.defaults['global_draw_color'])
  856. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  857. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  858. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(self.defaults['global_sel_draw_color'])
  859. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  860. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  861. #### End of Data ####
  862. #### Plot Area ####
  863. start_plot_time = time.time() # debug
  864. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  865. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  866. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  867. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  868. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  869. # Keys over plot enabled
  870. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  871. self.ui.splitter.setStretchFactor(1, 2)
  872. # So it can receive key presses
  873. self.plotcanvas.vispy_canvas.native.setFocus()
  874. self.app_cursor = self.plotcanvas.new_cursor()
  875. self.app_cursor.enabled = False
  876. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  877. # depending on from where those tools are called different actions can be done
  878. self.call_source = 'app'
  879. end_plot_time = time.time()
  880. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  881. ### EDITOR section
  882. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  883. self.exc_editor = FlatCAMExcEditor(self)
  884. #### Adjust tabs width ####
  885. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  886. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  887. self.collection.view.setMinimumWidth(290)
  888. self.log.debug("Finished adding Geometry and Excellon Editor's.")
  889. #### Worker ####
  890. self.workers = WorkerStack()
  891. self.worker_task.connect(self.workers.add_task)
  892. ### Signal handling ###
  893. ## Custom signals
  894. self.inform.connect(self.info)
  895. self.message.connect(self.message_dialog)
  896. self.progress.connect(self.set_progress_bar)
  897. self.object_created.connect(self.on_object_created)
  898. self.object_changed.connect(self.on_object_changed)
  899. self.object_plotted.connect(self.on_object_plotted)
  900. self.plots_updated.connect(self.on_plots_updated)
  901. self.file_opened.connect(self.register_recent)
  902. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  903. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  904. ## Standard signals
  905. # Menu
  906. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  907. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  908. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  909. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  910. self.ui.menufileopengerber_follow.triggered.connect(self.on_fileopengerber_follow)
  911. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  912. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  913. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  914. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  915. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  916. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  917. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  918. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  919. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  920. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  921. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  922. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  923. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  924. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  925. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  926. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  927. self.ui.menufile_exit.triggered.connect(self.on_app_exit)
  928. self.ui.menueditedit.triggered.connect(self.object2editor)
  929. self.ui.menueditok.triggered.connect(self.editor2object)
  930. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  931. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  932. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  933. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  934. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  935. self.ui.menueditdelete.triggered.connect(self.on_delete)
  936. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  937. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  938. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  939. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  940. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  941. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  942. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  943. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  944. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  945. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  946. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  947. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  948. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  949. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  950. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  951. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  952. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  953. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  954. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  955. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  956. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  957. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  958. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  959. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  960. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  961. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  962. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  963. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  964. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  965. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  966. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  967. self.ui.menuhelp_about.triggered.connect(self.on_about)
  968. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  969. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  970. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  971. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  972. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  973. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  974. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  975. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  976. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  977. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  978. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  979. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  980. # Toolbar
  981. #self.ui.file_new_btn.triggered.connect(self.on_file_new)
  982. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  983. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  984. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  985. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  986. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  987. self.ui.replot_btn.triggered.connect(self.plot_all)
  988. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  989. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  990. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  991. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  992. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  993. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  994. self.ui.update_obj_btn.triggered.connect(self.editor2object)
  995. self.ui.delete_btn.triggered.connect(self.on_delete)
  996. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  997. # Context Menu
  998. self.ui.popmenu_disable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  999. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1000. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1001. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1002. self.ui.draw_line.triggered.connect(self.geo_editor.draw_tool_path)
  1003. self.ui.draw_rect.triggered.connect(self.geo_editor.draw_tool_rectangle)
  1004. self.ui.draw_cut.triggered.connect(self.geo_editor.cutpath)
  1005. self.ui.draw_move.triggered.connect(self.geo_editor.on_move)
  1006. self.ui.drill.triggered.connect(self.exc_editor.exc_add_drill)
  1007. self.ui.drill_array.triggered.connect(self.exc_editor.exc_add_drill_array)
  1008. self.ui.drill_copy.triggered.connect(self.exc_editor.exc_copy_drills)
  1009. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1010. self.ui.clearplot.triggered.connect(self.clear_plots)
  1011. self.ui.replot.triggered.connect(self.plot_all)
  1012. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1013. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1014. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1015. self.ui.popmenu_save.triggered.connect(self.editor2object)
  1016. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1017. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1018. # Preferences Plot Area TAB
  1019. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1020. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1021. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1022. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1023. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1024. ###############################
  1025. ### GUI PREFERENCES SIGNALS ###
  1026. ###############################
  1027. self.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1028. self.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(self.on_language_apply)
  1029. ###############################
  1030. ### GUI PREFERENCES SIGNALS ###
  1031. ###############################
  1032. # Setting plot colors signals
  1033. self.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(self.on_pf_color_entry)
  1034. self.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(self.on_pf_color_button)
  1035. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(self.on_pf_color_spinner)
  1036. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(self.on_pf_color_slider)
  1037. self.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(self.on_pl_color_entry)
  1038. self.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(self.on_pl_color_button)
  1039. # Setting selection (left - right) colors signals
  1040. self.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(self.on_sf_color_entry)
  1041. self.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(self.on_sf_color_button)
  1042. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(self.on_sf_color_spinner)
  1043. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(self.on_sf_color_slider)
  1044. self.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(self.on_sl_color_entry)
  1045. self.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(self.on_sl_color_button)
  1046. # Setting selection (right - left) colors signals
  1047. self.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(self.on_alt_sf_color_entry)
  1048. self.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(self.on_alt_sf_color_button)
  1049. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1050. self.on_alt_sf_color_spinner)
  1051. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1052. self.on_alt_sf_color_slider)
  1053. self.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(self.on_alt_sl_color_entry)
  1054. self.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(self.on_alt_sl_color_button)
  1055. # Setting Editor Draw colors signals
  1056. self.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(self.on_draw_color_entry)
  1057. self.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(self.on_draw_color_button)
  1058. self.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(self.on_sel_draw_color_entry)
  1059. self.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(self.on_sel_draw_color_button)
  1060. self.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1061. self.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1062. self.general_defaults_form.general_gui_group.layout_combo.activated.connect(self.on_layout)
  1063. # Modify G-CODE Plot Area TAB
  1064. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1065. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1066. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1067. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1068. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1069. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1070. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1071. # Object list
  1072. self.collection.view.activated.connect(self.on_row_activated)
  1073. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1074. self.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1075. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1076. self.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1077. self.on_excellon_defaults_button)
  1078. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1079. self.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1080. self.on_excellon_options_button)
  1081. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1082. self.tool_tab_locked = False
  1083. # decide if to show or hide the Notebook side of the screen at startup
  1084. if self.defaults["global_project_at_startup"] is True:
  1085. self.ui.splitter.setSizes([1, 1])
  1086. else:
  1087. self.ui.splitter.setSizes([0, 1])
  1088. ####################
  1089. ### Other setups ###
  1090. ####################
  1091. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1092. self.setup_obj_classes()
  1093. self.setup_recent_items()
  1094. self.setup_component_editor()
  1095. #############
  1096. ### Shell ###
  1097. #############
  1098. ###
  1099. # Auto-complete KEYWORDS
  1100. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1101. 'aligndrill', 'clear',
  1102. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1103. 'export_gcode',
  1104. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1105. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1106. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1107. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1108. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1109. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1110. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1111. ]
  1112. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1113. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  1114. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  1115. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  1116. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  1117. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  1118. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  1119. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  1120. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1121. ]
  1122. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords
  1123. self.shell = FCShell(self, version=self.version)
  1124. self.shell._edit.set_model_data(self.myKeywords)
  1125. self.shell.setWindowIcon(self.ui.app_icon)
  1126. self.shell.setWindowTitle("FlatCAM Shell")
  1127. self.shell.resize(*self.defaults["global_shell_shape"])
  1128. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1129. self.shell.append_output("(Type help to get started)\n\n")
  1130. self.init_tcl()
  1131. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1132. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1133. self.ui.shell_dock.setWidget(self.shell)
  1134. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1135. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1136. QtWidgets.QDockWidget.DockWidgetFloatable |
  1137. QtWidgets.QDockWidget.DockWidgetClosable)
  1138. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1139. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1140. if self.defaults["global_shell_at_startup"]:
  1141. self.ui.shell_dock.show()
  1142. else:
  1143. self.ui.shell_dock.hide()
  1144. #########################
  1145. ### Tools and Plugins ###
  1146. #########################
  1147. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1148. self.install_tools()
  1149. ### System Font Parsing ###
  1150. # self.f_parse = ParseFont(self)
  1151. # self.parse_system_fonts()
  1152. # test if the program was started with a script as parameter
  1153. if self.cmd_line_shellfile:
  1154. try:
  1155. with open(self.cmd_line_shellfile, "r") as myfile:
  1156. cmd_line_shellfile_text = myfile.read()
  1157. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1158. except Exception as ext:
  1159. print("ERROR: ", ext)
  1160. sys.exit(2)
  1161. ###########################
  1162. #### Check for updates ####
  1163. ###########################
  1164. # Separate thread (Not worker)
  1165. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1166. if (self.beta is False or self.beta is None) and \
  1167. self.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1168. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1169. self.thr2 = QtCore.QThread()
  1170. self.worker_task.emit({'fcn': self.version_check,
  1171. 'params': []})
  1172. self.thr2.start()
  1173. ####################################
  1174. #### Variables for global usage ####
  1175. ####################################
  1176. # coordinates for relative position display
  1177. self.rel_point1 = (0, 0)
  1178. self.rel_point2 = (0, 0)
  1179. # variable to store coordinates
  1180. self.pos = (0, 0)
  1181. self.pos_jump = (0, 0)
  1182. # variable to store if there was motion before right mouse button click (panning)
  1183. self.panning_action = False
  1184. # variable to store if a command is active (then the var is not None) and which one it is
  1185. self.command_active = None
  1186. # variable to store the status of moving selection action
  1187. # None value means that it's not an selection action
  1188. # True value = a selection from left to right
  1189. # False value = a selection from right to left
  1190. self.selection_type = None
  1191. # List to store the objects that are currently loaded in FlatCAM
  1192. # This list is updated on each object creation or object delete
  1193. self.all_objects_list = []
  1194. # List to store the objects that are selected
  1195. self.sel_objects_list = []
  1196. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1197. self.key_modifiers = None
  1198. # Variable to hold the status of the axis
  1199. self.toggle_axis = True
  1200. # Variable to store the status of the fullscreen event
  1201. self.toggle_fscreen = False
  1202. self.cursor = None
  1203. # Variable to store the GCODE that was edited
  1204. self.gcode_edited = ""
  1205. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3', 'gko',
  1206. 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15', 'dim', 'mil',
  1207. 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo', 'art', 'gbd']
  1208. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1209. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1210. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1211. 'mpf']
  1212. self.svg_list = ['svg']
  1213. self.dxf_list = ['dxf']
  1214. self.prj_list = ['flatprj']
  1215. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1216. # flag for polygons not cleared
  1217. self.poly_not_cleared = False
  1218. ### Save defaults to factory_defaults.FlatConfig file ###
  1219. ### It's done only once after install #############
  1220. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1221. fac_def_from_file = factory_file.read()
  1222. factory_defaults = json.loads(fac_def_from_file)
  1223. # if the file contain an empty dictionary then save the factory defaults into the file
  1224. if not factory_defaults:
  1225. self.save_factory_defaults(silent=False)
  1226. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1227. self.on_layout(layout='compact')
  1228. factory_file.close()
  1229. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1230. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1231. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1232. # Post-GUI initialization: Experimental attempt
  1233. # to perform unit tests on the GUI.
  1234. # if post_gui is not None:
  1235. # post_gui(self)
  1236. App.log.debug("END of constructor. Releasing control.")
  1237. # accept a project file as command line parameter
  1238. # the path/file_name must be enclosed in quotes if it contain spaces
  1239. for argument in App.args:
  1240. if '.FlatPrj' in argument:
  1241. try:
  1242. project_name = str(argument)
  1243. if project_name == "":
  1244. self.inform.emit("Open cancelled.")
  1245. else:
  1246. # self.open_project(project_name)
  1247. run_from_arg = True
  1248. self.worker_task.emit({'fcn': self.open_project,
  1249. 'params': [project_name, run_from_arg]})
  1250. except Exception as e:
  1251. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1252. def defaults_read_form(self):
  1253. for option in self.defaults_form_fields:
  1254. try:
  1255. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1256. except:
  1257. pass
  1258. def defaults_write_form(self):
  1259. for option in self.defaults:
  1260. self.defaults_write_form_field(option)
  1261. # try:
  1262. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1263. # except KeyError:
  1264. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1265. # # TODO: Rethink this?
  1266. # pass
  1267. def defaults_write_form_field(self, field):
  1268. try:
  1269. self.defaults_form_fields[field].set_value(self.defaults[field])
  1270. except KeyError:
  1271. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1272. # TODO: Rethink this?
  1273. pass
  1274. def clear_pool(self):
  1275. self.pool.close()
  1276. self.pool = Pool()
  1277. self.pool_recreated.emit(self.pool)
  1278. gc.collect()
  1279. # the order that the tools are installed is important as they can depend on each other install position
  1280. def install_tools(self):
  1281. self.dblsidedtool = DblSidedTool(self)
  1282. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1283. self.measurement_tool = Measurement(self)
  1284. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1285. self.panelize_tool = Panelize(self)
  1286. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1287. self.film_tool = Film(self)
  1288. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'), separator=True)
  1289. self.move_tool = ToolMove(self)
  1290. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1291. before=self.ui.menueditorigin)
  1292. self.cutout_tool = ToolCutOut(self)
  1293. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16.png'), pos=self.ui.menutool,
  1294. before=self.measurement_tool.menuAction)
  1295. self.ncclear_tool = NonCopperClear(self)
  1296. self.ncclear_tool.install(icon=QtGui.QIcon('share/flatcam_icon16.png'), pos=self.ui.menutool,
  1297. before=self.measurement_tool.menuAction, separator=True)
  1298. self.paint_tool = ToolPaint(self)
  1299. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1300. before=self.measurement_tool.menuAction, separator=True)
  1301. self.calculator_tool = ToolCalculator(self)
  1302. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1303. self.transform_tool = ToolTransform(self)
  1304. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1305. self.properties_tool = Properties(self)
  1306. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1307. self.image_tool = ToolImage(self)
  1308. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1309. separator=True)
  1310. self.log.debug("Tools are installed.")
  1311. def remove_tools(self):
  1312. for act in self.ui.menutool.actions():
  1313. self.ui.menutool.removeAction(act)
  1314. def init_tools(self):
  1315. log.debug("init_tools()")
  1316. # delete the data currently in the Tools Tab and the Tab itself
  1317. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1318. if widget is not None:
  1319. widget.deleteLater()
  1320. self.ui.notebook.removeTab(2)
  1321. # rebuild the Tools Tab
  1322. self.ui.tool_tab = QtWidgets.QWidget()
  1323. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1324. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1325. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1326. self.ui.tool_scroll_area = VerticalScrollArea()
  1327. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1328. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1329. # first remove all of them
  1330. self.remove_tools()
  1331. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1332. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  1333. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1334. # third install all of them
  1335. self.install_tools()
  1336. self.log.debug("Tools are initialized.")
  1337. # def parse_system_fonts(self):
  1338. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1339. # 'params': []})
  1340. def object2editor(self):
  1341. """
  1342. Send the current Geometry or Excellon object (if any) into the editor.
  1343. :return: None
  1344. """
  1345. self.report_usage("object2editor()")
  1346. # adjust the visibility of some of the canvas context menu
  1347. self.ui.popmenu_edit.setVisible(False)
  1348. self.ui.popmenu_save.setVisible(True)
  1349. edited_object = self.collection.get_active()
  1350. if isinstance(edited_object, FlatCAMGeometry):
  1351. # for now, if the Geometry is MultiGeo do not allow the editing
  1352. if edited_object.multigeo is True:
  1353. self.inform.emit("[WARNING_NOTCL]Editing a MultiGeo Geometry is not possible for the moment.")
  1354. return
  1355. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1356. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1357. self.geo_editor.edit_fcgeometry(edited_object)
  1358. # set call source to the Editor we go into
  1359. self.call_source = 'geo_editor'
  1360. elif isinstance(edited_object, FlatCAMExcellon):
  1361. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1362. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1363. self.exc_editor.edit_fcexcellon(edited_object)
  1364. # set call source to the Editor we go into
  1365. self.call_source = 'exc_editor'
  1366. else:
  1367. self.inform.emit("[WARNING_NOTCL]Select a Geometry or Excellon Object to edit.")
  1368. return
  1369. # make sure that we can't select another object while in Editor Mode:
  1370. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1371. # delete any selection shape that might be active as they are not relevant in Editor
  1372. self.delete_selection_shape()
  1373. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1374. self.ui.plot_tab_area.protectTab(0)
  1375. self.inform.emit("[WARNING_NOTCL]Editor is activated ...")
  1376. self.should_we_save = True
  1377. def editor2object(self):
  1378. """
  1379. Transfers the Geometry or Excellon from the editor to the current object.
  1380. :return: None
  1381. """
  1382. self.report_usage("editor2object()")
  1383. # adjust the visibility of some of the canvas context menu
  1384. self.ui.popmenu_edit.setVisible(True)
  1385. self.ui.popmenu_save.setVisible(False)
  1386. edited_obj = self.collection.get_active()
  1387. obj_type = ""
  1388. if isinstance(edited_obj, FlatCAMGeometry):
  1389. obj_type = "Geometry"
  1390. self.geo_editor.update_fcgeometry(edited_obj)
  1391. self.geo_editor.update_options(edited_obj)
  1392. self.geo_editor.deactivate()
  1393. # update the geo object options so it is including the bounding box values
  1394. try:
  1395. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1396. edited_obj.options['xmin'] = xmin
  1397. edited_obj.options['ymin'] = ymin
  1398. edited_obj.options['xmax'] = xmax
  1399. edited_obj.options['ymax'] = ymax
  1400. except AttributeError:
  1401. self.inform.emit("[WARNING] Object empty after edit.")
  1402. elif isinstance(edited_obj, FlatCAMExcellon):
  1403. obj_type = "Excellon"
  1404. self.exc_editor.update_fcexcellon(edited_obj)
  1405. self.exc_editor.update_options(edited_obj)
  1406. self.exc_editor.deactivate()
  1407. else:
  1408. self.inform.emit("[WARNING_NOTCL]Select a Geometry or Excellon Object to update.")
  1409. return
  1410. # restore the call_source to app
  1411. self.call_source = 'app'
  1412. edited_obj.plot()
  1413. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1414. self.ui.plot_tab_area.protectTab(0)
  1415. self.inform.emit("[selected] %s is updated, returning to App..." % obj_type)
  1416. # reset the Object UI to original settings
  1417. # edited_obj.set_ui(edited_obj.ui_type())
  1418. # edited_obj.build_ui()
  1419. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1420. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1421. def get_last_folder(self):
  1422. return self.defaults["global_last_folder"]
  1423. def get_last_save_folder(self):
  1424. loc = self.defaults["global_last_save_folder"]
  1425. if loc is None:
  1426. loc = self.defaults["global_last_folder"]
  1427. if loc is None:
  1428. loc = os.path.dirname(__file__)
  1429. return loc
  1430. def report_usage(self, resource):
  1431. """
  1432. Increments usage counter for the given resource
  1433. in self.defaults['global_stats'].
  1434. :param resource: Name of the resource.
  1435. :return: None
  1436. """
  1437. if resource in self.defaults['global_stats']:
  1438. self.defaults['global_stats'][resource] += 1
  1439. else:
  1440. self.defaults['global_stats'][resource] = 1
  1441. def init_tcl(self):
  1442. if hasattr(self,'tcl'):
  1443. # self.tcl = None
  1444. # TODO we need to clean non default variables and procedures here
  1445. # new object cannot be used here as it will not remember values created for next passes,
  1446. # because tcl was execudted in old instance of TCL
  1447. pass
  1448. else:
  1449. self.tcl = tk.Tcl()
  1450. self.setup_shell()
  1451. self.log.debug("TCL Shell has been initialized.")
  1452. # TODO: This shouldn't be here.
  1453. class TclErrorException(Exception):
  1454. """
  1455. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1456. """
  1457. pass
  1458. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  1459. """
  1460. Shows a message on the FlatCAM Shell
  1461. :param msg: Message to display.
  1462. :param show: Opens the shell.
  1463. :param error: Shows the message as an error.
  1464. :return: None
  1465. """
  1466. if show:
  1467. self.ui.shell_dock.show()
  1468. try:
  1469. if error:
  1470. self.shell.append_error(msg + "\n")
  1471. elif warning:
  1472. self.shell.append_warning(msg + "\n")
  1473. elif success:
  1474. self.shell.append_success(msg + "\n")
  1475. elif selected:
  1476. self.shell.append_selected(msg + "\n")
  1477. else:
  1478. self.shell.append_output(msg + "\n")
  1479. except AttributeError:
  1480. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1481. def raise_tcl_unknown_error(self, unknownException):
  1482. """
  1483. Raise exception if is different type than TclErrorException
  1484. this is here mainly to show unknown errors inside TCL shell console.
  1485. :param unknownException:
  1486. :return:
  1487. """
  1488. if not isinstance(unknownException, self.TclErrorException):
  1489. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1490. else:
  1491. raise unknownException
  1492. def display_tcl_error(self, error, error_info=None):
  1493. """
  1494. escape bracket [ with \ otherwise there is error
  1495. "ERROR: missing close-bracket" instead of real error
  1496. :param error: it may be text or exception
  1497. :return: None
  1498. """
  1499. if isinstance(error, Exception):
  1500. exc_type, exc_value, exc_traceback = error_info
  1501. if not isinstance(error, self.TclErrorException):
  1502. show_trace = 1
  1503. else:
  1504. show_trace = int(self.defaults['global_verbose_error_level'])
  1505. if show_trace > 0:
  1506. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1507. trc_formated = []
  1508. for a in reversed(trc):
  1509. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1510. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1511. exc_type,
  1512. "\n".join(trc_formated))
  1513. else:
  1514. text = "%s" % error
  1515. else:
  1516. text = error
  1517. text = text.replace('[', '\\[').replace('"', '\\"')
  1518. self.tcl.eval('return -code error "%s"' % text)
  1519. def raise_tcl_error(self, text):
  1520. """
  1521. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1522. :param text: text of error
  1523. :return: raise exception
  1524. """
  1525. self.display_tcl_error(text)
  1526. raise self.TclErrorException(text)
  1527. def exec_command(self, text):
  1528. """
  1529. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1530. Also handles execution in separated threads
  1531. :param text:
  1532. :return: output if there was any
  1533. """
  1534. self.report_usage('exec_command')
  1535. result = self.exec_command_test(text, False)
  1536. #MS: added this method call so the geometry is updated once the TCL
  1537. #command is executed
  1538. self.plot_all()
  1539. return result
  1540. def exec_command_test(self, text, reraise=True):
  1541. """
  1542. Same as exec_command(...) with additional control over exceptions.
  1543. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1544. :param text: Input command
  1545. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1546. :return: Output from the command
  1547. """
  1548. text = str(text)
  1549. try:
  1550. self.shell.open_proccessing() # Disables input box.
  1551. result = self.tcl.eval(str(text))
  1552. if result != 'None':
  1553. self.shell.append_output(result + '\n')
  1554. except tk.TclError as e:
  1555. # This will display more precise answer if something in TCL shell fails
  1556. result = self.tcl.eval("set errorInfo")
  1557. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1558. self.shell.append_error('ERROR: ' + result + '\n')
  1559. # Show error in console and just return or in test raise exception
  1560. if reraise:
  1561. raise e
  1562. finally:
  1563. self.shell.close_proccessing()
  1564. pass
  1565. return result
  1566. # """
  1567. # Code below is unsused. Saved for later.
  1568. # """
  1569. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  1570. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  1571. # self.log.debug(parts)
  1572. # try:
  1573. # if parts[0] not in commands:
  1574. # self.shell.append_error("Unknown command\n")
  1575. # return
  1576. #
  1577. # #import inspect
  1578. # #inspect.getargspec(someMethod)
  1579. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  1580. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  1581. # self.shell.append_error(
  1582. # "Command %s takes %d arguments. %d given.\n" %
  1583. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  1584. # )
  1585. # return
  1586. #
  1587. # cmdfcn = commands[parts[0]]["fcn"]
  1588. # cmdconv = commands[parts[0]]["converters"]
  1589. # if len(parts) - 1 > 0:
  1590. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  1591. # else:
  1592. # retval = cmdfcn()
  1593. # retfcn = commands[parts[0]]["retfcn"]
  1594. # if retval and retfcn(retval):
  1595. # self.shell.append_output(retfcn(retval) + "\n")
  1596. #
  1597. # except Exception as e:
  1598. # #self.shell.append_error(''.join(traceback.format_exc()))
  1599. # #self.shell.append_error("?\n")
  1600. # self.shell.append_error(str(e) + "\n")
  1601. def info(self, msg):
  1602. """
  1603. Informs the user. Normally on the status bar, optionally
  1604. also on the shell.
  1605. :param msg: Text to write.
  1606. :return: None
  1607. """
  1608. # Type of message in brackets at the begining of the message.
  1609. match = re.search("\[([^\]]+)\](.*)", msg)
  1610. if match:
  1611. level = match.group(1)
  1612. msg_ = match.group(2)
  1613. self.ui.fcinfo.set_status(str(msg_), level=level)
  1614. if level.lower() == "error":
  1615. self.shell_message(msg, error=True, show=True)
  1616. elif level.lower() == "warning":
  1617. self.shell_message(msg, warning=True, show=True)
  1618. elif level.lower() == "error_notcl":
  1619. self.shell_message(msg, error=True, show=False)
  1620. elif level.lower() == "warning_notcl":
  1621. self.shell_message(msg, warning=True, show=False)
  1622. elif level.lower() == "success":
  1623. self.shell_message(msg, success=True, show=False)
  1624. elif level.lower() == "selected":
  1625. self.shell_message(msg, selected=True, show=False)
  1626. else:
  1627. self.shell_message(msg, show=False)
  1628. else:
  1629. self.ui.fcinfo.set_status(str(msg), level="info")
  1630. # make sure that if the message is to clear the infobar with a space
  1631. # is not printed over and over on the shell
  1632. if msg != '':
  1633. self.shell_message(msg)
  1634. def restore_toolbar_view(self):
  1635. tb = self.defaults["global_toolbar_view"]
  1636. if tb & 1:
  1637. self.ui.toolbarfile.setVisible(True)
  1638. else:
  1639. self.ui.toolbarfile.setVisible(False)
  1640. if tb & 2:
  1641. self.ui.toolbargeo.setVisible(True)
  1642. else:
  1643. self.ui.toolbargeo.setVisible(False)
  1644. if tb & 4:
  1645. self.ui.toolbarview.setVisible(True)
  1646. else:
  1647. self.ui.toolbarview.setVisible(False)
  1648. if tb & 8:
  1649. self.ui.toolbartools.setVisible(True)
  1650. else:
  1651. self.ui.toolbartools.setVisible(False)
  1652. if tb & 16:
  1653. self.ui.exc_edit_toolbar.setVisible(True)
  1654. else:
  1655. self.ui.exc_edit_toolbar.setVisible(False)
  1656. if tb & 32:
  1657. self.ui.geo_edit_toolbar.setVisible(True)
  1658. else:
  1659. self.ui.geo_edit_toolbar.setVisible(False)
  1660. if tb & 64:
  1661. self.ui.snap_toolbar.setVisible(True)
  1662. else:
  1663. self.ui.snap_toolbar.setVisible(False)
  1664. def load_defaults(self, filename):
  1665. """
  1666. Loads the aplication's default settings from current_defaults.FlatConfig into
  1667. ``self.defaults``.
  1668. :return: None
  1669. """
  1670. try:
  1671. f = open(self.data_path + "/" + filename + ".FlatConfig")
  1672. options = f.read()
  1673. f.close()
  1674. except IOError:
  1675. self.log.error("Could not load defaults file.")
  1676. self.inform.emit("[ERROR] Could not load defaults file.")
  1677. # in case the defaults file can't be loaded, show all toolbars
  1678. self.defaults["global_toolbar_view"] = 127
  1679. return
  1680. try:
  1681. defaults = json.loads(options)
  1682. except:
  1683. # in case the defaults file can't be loaded, show all toolbars
  1684. self.defaults["global_toolbar_view"] = 127
  1685. e = sys.exc_info()[0]
  1686. App.log.error(str(e))
  1687. self.inform.emit("[ERROR] Failed to parse defaults file.")
  1688. return
  1689. self.defaults.update(defaults)
  1690. log.debug("FlatCAM defaults loaded from: %s" % filename)
  1691. # restore the toolbar view
  1692. self.restore_toolbar_view()
  1693. def on_import_preferences(self):
  1694. """
  1695. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  1696. ``self.defaults``.
  1697. :return: None
  1698. """
  1699. self.report_usage("on_import_preferences")
  1700. App.log.debug("on_import_preferences()")
  1701. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1702. try:
  1703. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences",
  1704. directory=self.data_path, filter=filter)
  1705. except TypeError:
  1706. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences", filter=filter)
  1707. filename = str(filename)
  1708. if filename == "":
  1709. self.inform.emit("[WARNING_NOTCL]FlatCAM preferences import cancelled.")
  1710. else:
  1711. try:
  1712. f = open(filename)
  1713. options = f.read()
  1714. f.close()
  1715. except IOError:
  1716. self.log.error("Could not load defaults file.")
  1717. self.inform.emit("[ERROR_NOTCL] Could not load defaults file.")
  1718. return
  1719. try:
  1720. defaults_from_file = json.loads(options)
  1721. except:
  1722. e = sys.exc_info()[0]
  1723. App.log.error(str(e))
  1724. self.inform.emit("[ERROR_NOTCL] Failed to parse defaults file.")
  1725. return
  1726. self.defaults.update(defaults_from_file)
  1727. self.inform.emit("[success]Imported Defaults from %s" %filename)
  1728. def on_export_preferences(self):
  1729. self.report_usage("on_export_preferences")
  1730. App.log.debug("on_export_preferences()")
  1731. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1732. try:
  1733. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  1734. caption="Export FlatCAM Preferences",
  1735. directory=self.data_path + '/preferences_' + self.date.replace('-', ''), filter=filter
  1736. )
  1737. except TypeError:
  1738. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export FlatCAM Preferences", filter=filter)
  1739. filename = str(filename)
  1740. defaults_from_file = {}
  1741. if filename == "":
  1742. self.inform.emit("[WARNING_NOTCL]FlatCAM preferences export cancelled.")
  1743. return
  1744. else:
  1745. try:
  1746. f = open(filename, 'w')
  1747. defaults_file_content = f.read()
  1748. f.close()
  1749. except IOError:
  1750. App.log.debug('Creating a new preferences file ...')
  1751. f = open(filename, 'w')
  1752. json.dump({}, f)
  1753. f.close()
  1754. except:
  1755. e = sys.exc_info()[0]
  1756. App.log.error("Could not load defaults file.")
  1757. App.log.error(str(e))
  1758. self.inform.emit("[ERROR_NOTCL]Could not load defaults file.")
  1759. return
  1760. try:
  1761. defaults_from_file = json.loads(defaults_file_content)
  1762. except:
  1763. App.log.warning("Trying to read an empty Preferences file. Continue.")
  1764. # Update options
  1765. self.defaults_read_form()
  1766. defaults_from_file.update(self.defaults)
  1767. self.propagate_defaults(silent=True)
  1768. # Save update options
  1769. try:
  1770. f = open(filename, "w")
  1771. json.dump(defaults_from_file, f)
  1772. f.close()
  1773. except:
  1774. self.inform.emit("[ERROR_NOTCL] Failed to write defaults to file.")
  1775. return
  1776. self.file_saved.emit("preferences", filename)
  1777. self.inform.emit("[success]Exported Defaults to %s" % filename)
  1778. def on_preferences_open_folder(self):
  1779. self.report_usage("on_preferences_open_folder()")
  1780. if sys.platform == 'win32':
  1781. subprocess.Popen('explorer %s' % self.data_path)
  1782. elif sys.platform == 'darwin':
  1783. os.system('open "%s"' % self.data_path)
  1784. else:
  1785. subprocess.Popen(['xdg-open', self.data_path])
  1786. self.inform.emit("[success]FlatCAM Preferences Folder opened.")
  1787. def save_geometry(self, x, y, width, height, notebook_width):
  1788. self.defaults["global_def_win_x"] = x
  1789. self.defaults["global_def_win_y"] = y
  1790. self.defaults["global_def_win_w"] = width
  1791. self.defaults["global_def_win_h"] = height
  1792. self.defaults["def_notebook_width"] = notebook_width
  1793. self.save_defaults()
  1794. def message_dialog(self, title, message, kind="info"):
  1795. icon = {"info": QtWidgets.QMessageBox.Information,
  1796. "warning": QtWidgets.QMessageBox.Warning,
  1797. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  1798. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  1799. dlg.setText(message)
  1800. dlg.exec_()
  1801. def register_recent(self, kind, filename):
  1802. self.log.debug("register_recent()")
  1803. self.log.debug(" %s" % kind)
  1804. self.log.debug(" %s" % filename)
  1805. record = {'kind': str(kind), 'filename': str(filename)}
  1806. if record in self.recent:
  1807. return
  1808. self.recent.insert(0, record)
  1809. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  1810. self.recent.pop()
  1811. try:
  1812. f = open(self.data_path + '/recent.json', 'w')
  1813. except IOError:
  1814. App.log.error("Failed to open recent items file for writing.")
  1815. self.inform.emit('[ERROR_NOTCL]Failed to open recent files file for writing.')
  1816. return
  1817. #try:
  1818. json.dump(self.recent, f)
  1819. # except:
  1820. # App.log.error("Failed to write to recent items file.")
  1821. # self.inform.emit('ERROR: Failed to write to recent items file.')
  1822. # f.close()
  1823. f.close()
  1824. # Re-buid the recent items menu
  1825. self.setup_recent_items()
  1826. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  1827. """
  1828. Creates a new specalized FlatCAMObj and attaches it to the application,
  1829. this is, updates the GUI accordingly, any other records and plots it.
  1830. This method is thread-safe.
  1831. Notes:
  1832. * If the name is in use, the self.collection will modify it
  1833. when appending it to the collection. There is no need to handle
  1834. name conflicts here.
  1835. :param kind: The kind of object to create. One of 'gerber',
  1836. 'excellon', 'cncjob' and 'geometry'.
  1837. :type kind: str
  1838. :param name: Name for the object.
  1839. :type name: str
  1840. :param initialize: Function to run after creation of the object
  1841. but before it is attached to the application. The function is
  1842. called with 2 parameters: the new object and the App instance.
  1843. :type initialize: function
  1844. :return: None
  1845. :rtype: None
  1846. """
  1847. App.log.debug("new_object()")
  1848. self.plot = plot
  1849. self.autoselected = autoselected
  1850. t0 = time.time() # Debug
  1851. ## Create object
  1852. classdict = {
  1853. "gerber": FlatCAMGerber,
  1854. "excellon": FlatCAMExcellon,
  1855. "cncjob": FlatCAMCNCjob,
  1856. "geometry": FlatCAMGeometry
  1857. }
  1858. App.log.debug("Calling object constructor...")
  1859. obj = classdict[kind](name)
  1860. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  1861. # Set options from "Project options" form
  1862. self.options_read_form()
  1863. # IMPORTANT
  1864. # The key names in defaults and options dictionary's are not random:
  1865. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  1866. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  1867. # the options from project options form into the self.options. After that, below, depending on the type of
  1868. # object that is created, it will strip the name of the object and the underline (if the original key was
  1869. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  1870. # "toolchange"
  1871. for option in self.options:
  1872. if option.find(kind + "_") == 0:
  1873. oname = option[len(kind) + 1:]
  1874. obj.options[oname] = self.options[option]
  1875. # if kind == 'geometry':
  1876. # obj.tools = {}
  1877. # elif kind == 'cncjob':
  1878. # obj.cnc_tools = {}
  1879. # Initialize as per user request
  1880. # User must take care to implement initialize
  1881. # in a thread-safe way as is is likely that we
  1882. # have been invoked in a separate thread.
  1883. t1 = time.time()
  1884. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  1885. try:
  1886. return_value = initialize(obj, self)
  1887. except Exception as e:
  1888. msg = "[ERROR_NOTCL] An internal error has ocurred. See shell.\n"
  1889. msg += "Object (%s) failed because: %s \n\n" % (kind, str(e))
  1890. msg += traceback.format_exc()
  1891. self.inform.emit(msg)
  1892. # if str(e) == "Empty Geometry":
  1893. # self.inform.emit("[ERROR_NOTCL] )
  1894. # else:
  1895. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  1896. return "fail"
  1897. t2 = time.time()
  1898. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  1899. if return_value == 'fail':
  1900. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  1901. return "fail"
  1902. # Check units and convert if necessary
  1903. # This condition CAN be true because initialize() can change obj.units
  1904. if self.options["units"].upper() != obj.units.upper():
  1905. self.inform.emit("Converting units to " + self.options["units"] + ".")
  1906. obj.convert_units(self.options["units"])
  1907. t3 = time.time()
  1908. self.log.debug("%f seconds converting units." % (t3 - t2))
  1909. # Create the bounding box for the object and then add the results to the obj.options
  1910. try:
  1911. xmin, ymin, xmax, ymax = obj.bounds()
  1912. obj.options['xmin'] = xmin
  1913. obj.options['ymin'] = ymin
  1914. obj.options['xmax'] = xmax
  1915. obj.options['ymax'] = ymax
  1916. except:
  1917. log.warning("The object has no bounds properties.")
  1918. # don't plot objects with no bounds, there is nothing to plot
  1919. self.plot = False
  1920. pass
  1921. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  1922. # Move the object to the main thread and let the app know that it is available.
  1923. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  1924. self.object_created.emit(obj, self.plot, self.autoselected)
  1925. return obj
  1926. def new_excellon_object(self):
  1927. self.report_usage("new_excellon_object()")
  1928. self.new_object('excellon', 'new_e', lambda x, y: None, plot=False)
  1929. def new_geometry_object(self):
  1930. self.report_usage("new_geometry_object()")
  1931. def initialize(obj, self):
  1932. obj.multitool = False
  1933. self.new_object('geometry', 'new_g', initialize, plot=False)
  1934. def on_object_created(self, obj, plot, autoselect):
  1935. """
  1936. Event callback for object creation.
  1937. :param obj: The newly created FlatCAM object.
  1938. :return: None
  1939. """
  1940. t0 = time.time() # DEBUG
  1941. self.log.debug("on_object_created()")
  1942. # The Collection might change the name if there is a collision
  1943. self.collection.append(obj)
  1944. # after adding the object to the collection always update the list of objects that are in the collection
  1945. self.all_objects_list = self.collection.get_list()
  1946. # self.inform.emit('[selected] %s created & selected: %s' %
  1947. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  1948. if obj.kind == 'gerber':
  1949. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1950. (obj.kind.capitalize(), 'green', str(obj.options['name'])))
  1951. elif obj.kind == 'excellon':
  1952. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1953. (obj.kind.capitalize(), 'brown', str(obj.options['name'])))
  1954. elif obj.kind == 'cncjob':
  1955. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1956. (obj.kind.capitalize(), 'blue', str(obj.options['name'])))
  1957. elif obj.kind == 'geometry':
  1958. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  1959. (obj.kind.capitalize(), 'red', str(obj.options['name'])))
  1960. # self.new_object_available.emit(obj)
  1961. # update the SHELL auto-completer model with the name of the new object
  1962. self.myKeywords.append(obj.options['name'])
  1963. self.shell._edit.set_model_data(self.myKeywords)
  1964. if autoselect:
  1965. # select the just opened object but deselect the previous ones
  1966. self.collection.set_all_inactive()
  1967. self.collection.set_active(obj.options["name"])
  1968. # here it is done the object plotting
  1969. def worker_task(obj):
  1970. with self.proc_container.new("Plotting"):
  1971. if isinstance(obj, FlatCAMCNCjob):
  1972. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  1973. else:
  1974. obj.plot()
  1975. t1 = time.time() # DEBUG
  1976. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  1977. self.object_plotted.emit(obj)
  1978. # Send to worker
  1979. # self.worker.add_task(worker_task, [self])
  1980. if plot is True:
  1981. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  1982. def on_object_changed(self, obj):
  1983. # update the bounding box data from obj.options
  1984. xmin, ymin, xmax, ymax = obj.bounds()
  1985. obj.options['xmin'] = xmin
  1986. obj.options['ymin'] = ymin
  1987. obj.options['xmax'] = xmax
  1988. obj.options['ymax'] = ymax
  1989. log.debug("Object changed, updating the bounding box data on self.options")
  1990. # delete the old selection shape
  1991. self.delete_selection_shape()
  1992. self.should_we_save = True
  1993. def on_object_plotted(self, obj):
  1994. self.on_zoom_fit(None)
  1995. def options_read_form(self):
  1996. for option in self.options_form_fields:
  1997. self.options[option] = self.options_form_fields[option].get_value()
  1998. def options_write_form(self):
  1999. for option in self.options:
  2000. self.options_write_form_field(option)
  2001. def options_write_form_field(self, field):
  2002. try:
  2003. self.options_form_fields[field].set_value(self.options[field])
  2004. except KeyError:
  2005. # Changed from error to debug. This allows to have data stored
  2006. # which is not user-editable.
  2007. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2008. pass
  2009. def on_about(self):
  2010. """
  2011. Displays the "about" dialog.
  2012. :return: None
  2013. """
  2014. self.report_usage("on_about")
  2015. version = self.version
  2016. version_date = self.version_date
  2017. beta = self.beta
  2018. class AboutDialog(QtWidgets.QDialog):
  2019. def __init__(self, parent=None):
  2020. QtWidgets.QDialog.__init__(self, parent)
  2021. # Icon and title
  2022. self.setWindowIcon(parent.app_icon)
  2023. self.setWindowTitle("FlatCAM")
  2024. layout1 = QtWidgets.QVBoxLayout()
  2025. self.setLayout(layout1)
  2026. layout2 = QtWidgets.QHBoxLayout()
  2027. layout1.addLayout(layout2)
  2028. logo = QtWidgets.QLabel()
  2029. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2030. layout2.addWidget(logo, stretch=0)
  2031. title = QtWidgets.QLabel(
  2032. "<font size=8><B>FlatCAM</B></font><BR>"
  2033. "Version %s %s (%s) - %s <BR>"
  2034. "<BR>"
  2035. "2D Computer-Aided Printed Circuit Board<BR>"
  2036. "Manufacturing.<BR>"
  2037. "<BR>"
  2038. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2039. "<BR>"
  2040. "<B> Main Contributors:</B><BR>"
  2041. "Denis Hayrullin<BR>"
  2042. "Kamil Sopko<BR>"
  2043. "Marius Stanciu<BR>"
  2044. "Matthieu Berthomé<BR>"
  2045. "and many others found "
  2046. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2047. "<BR>"
  2048. "Development is done "
  2049. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2050. "DOWNLOAD area "
  2051. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2052. "" % (version, ('BETA' if beta else ''), version_date, platform.architecture()[0])
  2053. )
  2054. title.setOpenExternalLinks(True)
  2055. layout2.addWidget(title, stretch=1)
  2056. layout3 = QtWidgets.QHBoxLayout()
  2057. layout1.addLayout(layout3)
  2058. layout3.addStretch()
  2059. okbtn = QtWidgets.QPushButton("Close")
  2060. layout3.addWidget(okbtn)
  2061. okbtn.clicked.connect(self.accept)
  2062. AboutDialog(self.ui).exec_()
  2063. def on_file_savedefaults(self):
  2064. """
  2065. Callback for menu item File->Save Defaults. Saves application default options
  2066. ``self.defaults`` to current_defaults.FlatConfig.
  2067. :return: None
  2068. """
  2069. self.save_defaults()
  2070. def on_app_exit(self):
  2071. self.report_usage("on_app_exit()")
  2072. if self.collection.get_list():
  2073. msgbox = QtWidgets.QMessageBox()
  2074. # msgbox.setText("<B>Save changes ...</B>")
  2075. msgbox.setText("There are files/objects opened in FlatCAM. "
  2076. "\n"
  2077. "Do you want to Save the project?")
  2078. msgbox.setWindowTitle("Save changes")
  2079. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2080. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2081. QtWidgets.QMessageBox.Cancel)
  2082. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2083. response = msgbox.exec_()
  2084. if response == QtWidgets.QMessageBox.Yes:
  2085. self.on_file_saveprojectas(thread=False)
  2086. elif response == QtWidgets.QMessageBox.Cancel:
  2087. return
  2088. self.save_defaults()
  2089. else:
  2090. self.save_defaults()
  2091. log.debug("Application defaults saved ... Exit event.")
  2092. QtWidgets.qApp.quit()
  2093. def save_defaults(self, silent=False):
  2094. """
  2095. Saves application default options
  2096. ``self.defaults`` to current_defaults.FlatConfig.
  2097. :return: None
  2098. """
  2099. self.report_usage("save_defaults")
  2100. # Read options from file
  2101. try:
  2102. f = open(self.data_path + "/current_defaults.FlatConfig")
  2103. defaults_file_content = f.read()
  2104. f.close()
  2105. except:
  2106. e = sys.exc_info()[0]
  2107. App.log.error("Could not load defaults file.")
  2108. App.log.error(str(e))
  2109. self.inform.emit("[ERROR_NOTCL] Could not load defaults file.")
  2110. return
  2111. try:
  2112. defaults = json.loads(defaults_file_content)
  2113. except:
  2114. e = sys.exc_info()[0]
  2115. App.log.error("Failed to parse defaults file.")
  2116. App.log.error(str(e))
  2117. self.inform.emit("[ERROR_NOTCL] Failed to parse defaults file.")
  2118. return
  2119. # Update options
  2120. self.defaults_read_form()
  2121. defaults.update(self.defaults)
  2122. self.propagate_defaults(silent=True)
  2123. # Save update options
  2124. try:
  2125. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  2126. json.dump(defaults, f)
  2127. f.close()
  2128. except:
  2129. self.inform.emit("[ERROR_NOTCL] Failed to write defaults to file.")
  2130. return
  2131. # Save the toolbar view
  2132. tb_status = 0
  2133. if self.ui.toolbarfile.isVisible():
  2134. tb_status += 1
  2135. if self.ui.toolbargeo.isVisible():
  2136. tb_status += 2
  2137. if self.ui.toolbarview.isVisible():
  2138. tb_status += 4
  2139. if self.ui.toolbartools.isVisible():
  2140. tb_status += 8
  2141. if self.ui.exc_edit_toolbar.isVisible():
  2142. tb_status += 16
  2143. if self.ui.geo_edit_toolbar.isVisible():
  2144. tb_status += 32
  2145. if self.ui.snap_toolbar.isVisible():
  2146. tb_status += 64
  2147. self.defaults["global_toolbar_view"] = tb_status
  2148. if not silent:
  2149. self.inform.emit("[success]Defaults saved.")
  2150. def save_factory_defaults(self, silent=False):
  2151. """
  2152. Saves application factory default options
  2153. ``self.defaults`` to factory_defaults.FlatConfig.
  2154. It's a one time job done just after the first install.
  2155. :return: None
  2156. """
  2157. self.report_usage("save_factory_defaults")
  2158. # Read options from file
  2159. try:
  2160. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2161. factory_defaults_file_content = f_f_def.read()
  2162. f_f_def.close()
  2163. except:
  2164. e = sys.exc_info()[0]
  2165. App.log.error("Could not load factory defaults file.")
  2166. App.log.error(str(e))
  2167. self.inform.emit("[ERROR_NOTCL] Could not load factory defaults file.")
  2168. return
  2169. try:
  2170. factory_defaults = json.loads(factory_defaults_file_content)
  2171. except:
  2172. e = sys.exc_info()[0]
  2173. App.log.error("Failed to parse factory defaults file.")
  2174. App.log.error(str(e))
  2175. self.inform.emit("[ERROR_NOTCL] Failed to parse factory defaults file.")
  2176. return
  2177. # Update options
  2178. self.defaults_read_form()
  2179. factory_defaults.update(self.defaults)
  2180. self.propagate_defaults(silent=True)
  2181. # Save update options
  2182. try:
  2183. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2184. json.dump(factory_defaults, f_f_def_s)
  2185. f_f_def_s.close()
  2186. except:
  2187. self.inform.emit("[ERROR_NOTCL] Failed to write factory defaults to file.")
  2188. return
  2189. if silent is False:
  2190. self.inform.emit("Factory defaults saved.")
  2191. def final_save(self):
  2192. if self.should_we_save and self.collection.get_list():
  2193. msgbox = QtWidgets.QMessageBox()
  2194. # msgbox.setText("<B>Save changes ...</B>")
  2195. msgbox.setText("There are files/objects modified in FlatCAM. "
  2196. "\n"
  2197. "Do you want to Save the project?")
  2198. msgbox.setWindowTitle("Save changes")
  2199. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2200. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2201. QtWidgets.QMessageBox.Cancel)
  2202. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2203. response = msgbox.exec_()
  2204. if response == QtWidgets.QMessageBox.Yes:
  2205. self.on_file_saveprojectas(thread=False)
  2206. elif response == QtWidgets.QMessageBox.Cancel:
  2207. self.should_we_quit = False
  2208. return
  2209. self.save_defaults()
  2210. log.debug("Application defaults saved ... Exit event.")
  2211. def on_toggle_shell(self):
  2212. """
  2213. toggle shell if is visible close it if closed open it
  2214. :return:
  2215. """
  2216. self.report_usage("on_toggle_shell()")
  2217. if self.ui.shell_dock.isVisible():
  2218. self.ui.shell_dock.hide()
  2219. else:
  2220. self.ui.shell_dock.show()
  2221. def on_edit_join(self, name=None):
  2222. """
  2223. Callback for Edit->Join. Joins the selected geometry objects into
  2224. a new one.
  2225. :return: None
  2226. """
  2227. self.report_usage("on_edit_join()")
  2228. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2229. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2230. tooldias = []
  2231. geo_type_list = []
  2232. objs = self.collection.get_selected()
  2233. for obj in objs:
  2234. geo_type_list.append(obj.multigeo)
  2235. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2236. if len(set(geo_type_list)) != 1:
  2237. self.inform.emit("[ERROR] Failed join. The Geometry objects are of different types.\n"
  2238. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2239. "convert from one to another and retry joining \n"
  2240. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2241. "the result may not be what was expected. \n"
  2242. "Check the generated GCODE.")
  2243. return
  2244. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2245. if True in geo_type_list:
  2246. def initialize(obj, app):
  2247. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2248. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2249. for v in obj.tools.values():
  2250. v['data']['name'] = obj_name_multi
  2251. self.new_object("geometry", obj_name_multi, initialize)
  2252. else:
  2253. def initialize(obj, app):
  2254. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2255. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2256. for v in obj.tools.values():
  2257. v['data']['name'] = obj_name_single
  2258. self.new_object("geometry", obj_name_single, initialize)
  2259. self.should_we_save = True
  2260. def on_edit_join_exc(self):
  2261. """
  2262. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2263. a new one.
  2264. :return: None
  2265. """
  2266. self.report_usage("on_edit_join_exc()")
  2267. objs = self.collection.get_selected()
  2268. for obj in objs:
  2269. if not isinstance(obj, FlatCAMExcellon):
  2270. self.inform.emit("[ERROR_NOTCL]Failed. Excellon joining works only on Excellon objects.")
  2271. return
  2272. def initialize(obj, app):
  2273. FlatCAMExcellon.merge(objs, obj)
  2274. self.new_object("excellon", 'Combo_Excellon', initialize)
  2275. self.should_we_save = True
  2276. def on_edit_join_grb(self):
  2277. """
  2278. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2279. a new one.
  2280. :return: None
  2281. """
  2282. self.report_usage("on_edit_join_grb()")
  2283. objs = self.collection.get_selected()
  2284. for obj in objs:
  2285. if not isinstance(obj, FlatCAMGerber):
  2286. self.inform.emit("[ERROR_NOTCL]Failed. Gerber joining works only on Gerber objects.")
  2287. return
  2288. def initialize(obj, app):
  2289. FlatCAMGerber.merge(objs, obj)
  2290. self.new_object("gerber", 'Combo_Gerber', initialize)
  2291. self.should_we_save = True
  2292. def on_convert_singlegeo_to_multigeo(self):
  2293. self.report_usage("on_convert_singlegeo_to_multigeo()")
  2294. obj = self.collection.get_active()
  2295. if obj is None:
  2296. self.inform.emit("[ERROR_NOTCL]Failed. Select a Geometry Object and try again.")
  2297. return
  2298. if not isinstance(obj, FlatCAMGeometry):
  2299. self.inform.emit("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s" % type(obj))
  2300. return
  2301. obj.multigeo = True
  2302. for tooluid, dict_value in obj.tools.items():
  2303. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2304. if not isinstance(obj.solid_geometry, list):
  2305. obj.solid_geometry = [obj.solid_geometry]
  2306. obj.solid_geometry[:] = []
  2307. obj.plot()
  2308. self.should_we_save = True
  2309. self.inform.emit("[success] A Geometry object was converted to MultiGeo type.")
  2310. def on_convert_multigeo_to_singlegeo(self):
  2311. self.report_usage("on_convert_multigeo_to_singlegeo()")
  2312. obj = self.collection.get_active()
  2313. if obj is None:
  2314. self.inform.emit("[ERROR_NOTCL]Failed. Select a Geometry Object and try again.")
  2315. return
  2316. if not isinstance(obj, FlatCAMGeometry):
  2317. self.inform.emit("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s" % type(obj))
  2318. return
  2319. obj.multigeo = False
  2320. total_solid_geometry = []
  2321. for tooluid, dict_value in obj.tools.items():
  2322. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2323. # clear the original geometry
  2324. dict_value['solid_geometry'][:] = []
  2325. obj.solid_geometry = deepcopy(total_solid_geometry)
  2326. obj.plot()
  2327. self.should_we_save = True
  2328. self.inform.emit("[success] A Geometry object was converted to SingleGeo type.")
  2329. def on_options_dict_change(self, field):
  2330. self.options_write_form_field(field)
  2331. if field == "units":
  2332. self.set_screen_units(self.options['units'])
  2333. def on_defaults_dict_change(self, field):
  2334. self.defaults_write_form_field(field)
  2335. def set_screen_units(self, units):
  2336. self.ui.units_label.setText("[" + self.options["units"].lower() + "]")
  2337. def on_toggle_units(self):
  2338. """
  2339. Callback for the Units radio-button change in the Options tab.
  2340. Changes the application's default units or the current project's units.
  2341. If changing the project's units, the change propagates to all of
  2342. the objects in the project.
  2343. :return: None
  2344. """
  2345. self.report_usage("on_toggle_units")
  2346. if self.toggle_units_ignore:
  2347. return
  2348. # If option is the same, then ignore
  2349. if self.general_options_form.general_app_group.units_radio.get_value().upper() == self.options["units"].upper():
  2350. self.log.debug("on_toggle_units(): Same as options, so ignoring.")
  2351. return
  2352. # Options to scale
  2353. dimensions = ['gerber_isotooldia', 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2354. 'gerber_noncoppermargin', 'gerber_bboxmargin','gerber_isooverlap','tools_nccoverlap',
  2355. 'tools_nccmargin','tools_cutouttooldia','tools_cutoutgapsize',
  2356. 'gerber_noncoppermargin','gerber_bboxmargin',
  2357. 'excellon_drillz', "excellon_toolchangexy",
  2358. 'excellon_travelz', 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2359. 'excellon_tooldia', 'excellon_endz', 'cncjob_tooldia',
  2360. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate', 'geometry_feedrate_rapid',
  2361. 'geometry_cnctooldia', 'tools_painttooldia', 'tools_paintoverlap', 'geometry_toolchangexy',
  2362. 'geometry_toolchangez',
  2363. 'tools_paintmargin', 'geometry_endz', 'geometry_depthperpass', 'global_gridx', 'global_gridy']
  2364. def scale_options(sfactor):
  2365. for dim in dimensions:
  2366. if dim == 'excellon_toolchangexy':
  2367. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2368. coords_xy[0] *= sfactor
  2369. coords_xy[1] *= sfactor
  2370. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2371. elif dim == 'geometry_toolchangexy':
  2372. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2373. coords_xy[0] *= sfactor
  2374. coords_xy[1] *= sfactor
  2375. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2376. else:
  2377. self.options[dim] *= sfactor
  2378. # The scaling factor depending on choice of units.
  2379. factor = 1/25.4
  2380. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2381. factor = 25.4
  2382. # Changing project units. Warn user.
  2383. msgbox = QtWidgets.QMessageBox()
  2384. msgbox.setText("<B>Change project units ...</B>")
  2385. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  2386. "properties of all objects to be scaled accordingly. Continue?")
  2387. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  2388. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2389. response = msgbox.exec_()
  2390. if response == QtWidgets.QMessageBox.Ok:
  2391. self.options_read_form()
  2392. scale_options(factor)
  2393. self.options_write_form()
  2394. self.should_we_save = True
  2395. # change this only if the workspace is active
  2396. if self.defaults['global_workspace'] is True:
  2397. self.plotcanvas.draw_workspace()
  2398. # adjust the grid values on the main toolbar
  2399. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  2400. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2401. for obj in self.collection.get_list():
  2402. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  2403. obj.convert_units(units)
  2404. # make that the properties stored in the object are also updated
  2405. self.object_changed.emit(obj)
  2406. obj.build_ui()
  2407. current = self.collection.get_active()
  2408. if current is not None:
  2409. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2410. if not isinstance(current, FlatCAMGeometry):
  2411. current.to_form()
  2412. self.plot_all()
  2413. self.inform.emit("[success]Converted units to %s" % self.options["units"])
  2414. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  2415. self.set_screen_units(self.options["units"])
  2416. else:
  2417. # Undo toggling
  2418. self.toggle_units_ignore = True
  2419. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2420. self.general_options_form.general_app_group.units_radio.set_value('IN')
  2421. else:
  2422. self.general_options_form.general_app_group.units_radio.set_value('MM')
  2423. self.toggle_units_ignore = False
  2424. self.inform.emit("[WARNING_NOTCL]Units conversion cancelled.")
  2425. self.options_read_form()
  2426. def on_toggle_units_click(self):
  2427. if self.options["units"] == 'MM':
  2428. self.general_options_form.general_app_group.units_radio.set_value("IN")
  2429. else:
  2430. self.general_options_form.general_app_group.units_radio.set_value("MM")
  2431. self.on_toggle_units()
  2432. def on_language_apply(self):
  2433. self.report_usage("on_language_apply()")
  2434. # TODO: apply the language
  2435. # app restart section
  2436. pass
  2437. def on_fullscreen(self):
  2438. self.report_usage("on_fullscreen()")
  2439. if self.toggle_fscreen is False:
  2440. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  2441. tb.setVisible(False)
  2442. self.ui.splitter_left.setVisible(False)
  2443. self.toggle_fscreen = True
  2444. else:
  2445. self.restore_toolbar_view()
  2446. self.ui.splitter_left.setVisible(True)
  2447. self.toggle_fscreen = False
  2448. def on_toggle_plotarea(self):
  2449. self.report_usage("on_toggle_plotarea()")
  2450. try:
  2451. name = self.ui.plot_tab_area.widget(0).objectName()
  2452. except AttributeError:
  2453. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  2454. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2455. self.ui.plot_tab_area.protectTab(0)
  2456. return
  2457. if name != 'plotarea':
  2458. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  2459. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2460. self.ui.plot_tab_area.protectTab(0)
  2461. else:
  2462. self.ui.plot_tab_area.closeTab(0)
  2463. def on_toggle_notebook(self):
  2464. if self.ui.splitter.sizes()[0] == 0:
  2465. self.ui.splitter.setSizes([1, 1])
  2466. else:
  2467. self.ui.splitter.setSizes([0, 1])
  2468. def on_toggle_axis(self):
  2469. self.report_usage("on_toggle_axis()")
  2470. if self.toggle_axis is False:
  2471. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2472. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2473. self.plotcanvas.redraw()
  2474. self.toggle_axis = True
  2475. else:
  2476. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2477. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2478. self.plotcanvas.redraw()
  2479. self.toggle_axis = False
  2480. def on_toggle_grid(self):
  2481. self.report_usage("on_toggle_grid()")
  2482. self.ui.grid_snap_btn.trigger()
  2483. def on_options_combo_change(self, sel):
  2484. """
  2485. Called when the combo box to choose between application defaults and
  2486. project option changes value. The corresponding variables are
  2487. copied to the UI.
  2488. :param sel: The option index that was chosen.
  2489. :return: None
  2490. """
  2491. # combo_sel = self.ui.notebook.combo_options.get_active()
  2492. App.log.debug("Options --> %s" % sel)
  2493. # form = [self.defaults_form, self.options_form][sel]
  2494. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  2495. if sel == 0:
  2496. self.gen_form = self.general_defaults_form
  2497. self.ger_form = self.gerber_defaults_form
  2498. self.exc_form = self.excellon_defaults_form
  2499. self.geo_form = self.geometry_defaults_form
  2500. self.cnc_form = self.cncjob_defaults_form
  2501. self.tools_form = self.tools_defaults_form
  2502. elif sel == 1:
  2503. self.gen_form = self.general_options_form
  2504. self.ger_form = self.gerber_options_form
  2505. self.exc_form = self.excellon_options_form
  2506. self.geo_form = self.geometry_options_form
  2507. self.cnc_form = self.cncjob_options_form
  2508. self.tools_form = self.tools_options_form
  2509. else:
  2510. return
  2511. try:
  2512. self.ui.general_scroll_area.takeWidget()
  2513. except:
  2514. self.log.debug("Nothing to remove")
  2515. self.ui.general_scroll_area.setWidget(self.gen_form)
  2516. self.gen_form.show()
  2517. try:
  2518. self.ui.gerber_scroll_area.takeWidget()
  2519. except:
  2520. self.log.debug("Nothing to remove")
  2521. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  2522. self.ger_form.show()
  2523. try:
  2524. self.ui.excellon_scroll_area.takeWidget()
  2525. except:
  2526. self.log.debug("Nothing to remove")
  2527. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  2528. self.exc_form.show()
  2529. try:
  2530. self.ui.geometry_scroll_area.takeWidget()
  2531. except:
  2532. self.log.debug("Nothing to remove")
  2533. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  2534. self.geo_form.show()
  2535. try:
  2536. self.ui.cncjob_scroll_area.takeWidget()
  2537. except:
  2538. self.log.debug("Nothing to remove")
  2539. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  2540. self.cnc_form.show()
  2541. try:
  2542. self.ui.tools_scroll_area.takeWidget()
  2543. except:
  2544. self.log.debug("Nothing to remove")
  2545. self.ui.tools_scroll_area.setWidget(self.tools_form)
  2546. self.tools_form.show()
  2547. self.log.debug("Finished GUI form initialization.")
  2548. # self.options2form()
  2549. def on_excellon_defaults_button(self):
  2550. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  2551. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  2552. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  2553. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  2554. self.defaults_form_fields["excellon_zeros"].set_value('L')
  2555. self.defaults_form_fields["excellon_units"].set_value('INCH')
  2556. log.debug("Excellon app defaults loaded ...")
  2557. def on_excellon_options_button(self):
  2558. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  2559. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  2560. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  2561. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  2562. self.options_form_fields["excellon_zeros"].set_value('L')
  2563. self.options_form_fields["excellon_units"].set_value('INCH')
  2564. log.debug("Excellon options defaults loaded ...")
  2565. # Setting plot colors handlers
  2566. def on_pf_color_entry(self):
  2567. self.defaults['global_plot_fill'] = self.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  2568. self.defaults['global_plot_fill'][7:9]
  2569. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2570. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  2571. def on_pf_color_button(self):
  2572. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  2573. c_dialog = QtWidgets.QColorDialog()
  2574. plot_fill_color = c_dialog.getColor(initial=current_color)
  2575. if plot_fill_color.isValid() is False:
  2576. return
  2577. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2578. "background-color:%s" % str(plot_fill_color.name()))
  2579. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  2580. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  2581. self.defaults['global_plot_fill'] = new_val
  2582. def on_pf_color_spinner(self):
  2583. spinner_value = self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  2584. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  2585. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  2586. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2587. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  2588. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2589. def on_pf_color_slider(self):
  2590. slider_value = self.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  2591. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  2592. def on_pl_color_entry(self):
  2593. self.defaults['global_plot_line'] = self.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  2594. self.defaults['global_plot_line'][7:9]
  2595. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2596. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  2597. def on_pl_color_button(self):
  2598. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  2599. # print(current_color)
  2600. c_dialog = QtWidgets.QColorDialog()
  2601. plot_line_color = c_dialog.getColor(initial=current_color)
  2602. if plot_line_color.isValid() is False:
  2603. return
  2604. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2605. "background-color:%s" % str(plot_line_color.name()))
  2606. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  2607. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  2608. self.defaults['global_plot_line'] = new_val_line
  2609. # Setting selection colors (left - right) handlers
  2610. def on_sf_color_entry(self):
  2611. self.defaults['global_sel_fill'] = self.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  2612. self.defaults['global_sel_fill'][7:9]
  2613. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2614. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  2615. def on_sf_color_button(self):
  2616. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  2617. c_dialog = QtWidgets.QColorDialog()
  2618. plot_fill_color = c_dialog.getColor(initial=current_color)
  2619. if plot_fill_color.isValid() is False:
  2620. return
  2621. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2622. "background-color:%s" % str(plot_fill_color.name()))
  2623. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  2624. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  2625. self.defaults['global_sel_fill'] = new_val
  2626. def on_sf_color_spinner(self):
  2627. spinner_value = self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  2628. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  2629. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  2630. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2631. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  2632. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2633. def on_sf_color_slider(self):
  2634. slider_value = self.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  2635. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  2636. def on_sl_color_entry(self):
  2637. self.defaults['global_sel_line'] = self.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  2638. self.defaults['global_sel_line'][7:9]
  2639. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2640. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  2641. def on_sl_color_button(self):
  2642. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  2643. c_dialog = QtWidgets.QColorDialog()
  2644. plot_line_color = c_dialog.getColor(initial=current_color)
  2645. if plot_line_color.isValid() is False:
  2646. return
  2647. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2648. "background-color:%s" % str(plot_line_color.name()))
  2649. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  2650. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  2651. self.defaults['global_sel_line'] = new_val_line
  2652. # Setting selection colors (right - left) handlers
  2653. def on_alt_sf_color_entry(self):
  2654. self.defaults['global_alt_sel_fill'] = self.general_defaults_form.general_gui_group \
  2655. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  2656. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2657. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  2658. def on_alt_sf_color_button(self):
  2659. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  2660. c_dialog = QtWidgets.QColorDialog()
  2661. plot_fill_color = c_dialog.getColor(initial=current_color)
  2662. if plot_fill_color.isValid() is False:
  2663. return
  2664. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2665. "background-color:%s" % str(plot_fill_color.name()))
  2666. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  2667. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  2668. self.defaults['global_alt_sel_fill'] = new_val
  2669. def on_alt_sf_color_spinner(self):
  2670. spinner_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  2671. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  2672. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  2673. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2674. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  2675. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2676. def on_alt_sf_color_slider(self):
  2677. slider_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  2678. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  2679. def on_alt_sl_color_entry(self):
  2680. self.defaults['global_alt_sel_line'] = self.general_defaults_form.general_gui_group \
  2681. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  2682. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2683. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  2684. def on_alt_sl_color_button(self):
  2685. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  2686. c_dialog = QtWidgets.QColorDialog()
  2687. plot_line_color = c_dialog.getColor(initial=current_color)
  2688. if plot_line_color.isValid() is False:
  2689. return
  2690. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2691. "background-color:%s" % str(plot_line_color.name()))
  2692. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  2693. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  2694. self.defaults['global_alt_sel_line'] = new_val_line
  2695. # Setting Editor colors
  2696. def on_draw_color_entry(self):
  2697. self.defaults['global_draw_color'] = self.general_defaults_form.general_gui_group \
  2698. .draw_color_entry.get_value()
  2699. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2700. "background-color:%s" % str(self.defaults['global_draw_color']))
  2701. def on_draw_color_button(self):
  2702. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  2703. c_dialog = QtWidgets.QColorDialog()
  2704. draw_color = c_dialog.getColor(initial=current_color)
  2705. if draw_color.isValid() is False:
  2706. return
  2707. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2708. "background-color:%s" % str(draw_color.name()))
  2709. new_val = str(draw_color.name())
  2710. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  2711. self.defaults['global_draw_color'] = new_val
  2712. def on_sel_draw_color_entry(self):
  2713. self.defaults['global_sel_draw_color'] = self.general_defaults_form.general_gui_group \
  2714. .sel_draw_color_entry.get_value()
  2715. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2716. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  2717. def on_sel_draw_color_button(self):
  2718. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  2719. c_dialog = QtWidgets.QColorDialog()
  2720. sel_draw_color = c_dialog.getColor(initial=current_color)
  2721. if sel_draw_color.isValid() is False:
  2722. return
  2723. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2724. "background-color:%s" % str(sel_draw_color.name()))
  2725. new_val_sel = str(sel_draw_color.name())
  2726. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  2727. self.defaults['global_sel_draw_color'] = new_val_sel
  2728. def on_deselect_all(self):
  2729. self.collection.set_all_inactive()
  2730. self.delete_selection_shape()
  2731. def on_workspace_modified(self):
  2732. self.save_defaults(silent=True)
  2733. self.plotcanvas.draw_workspace()
  2734. def on_workspace(self):
  2735. self.report_usage("on_workspace()")
  2736. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2737. self.plotcanvas.restore_workspace()
  2738. else:
  2739. self.plotcanvas.delete_workspace()
  2740. self.save_defaults(silent=True)
  2741. def on_workspace_menu(self):
  2742. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2743. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  2744. else:
  2745. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  2746. self.on_workspace()
  2747. def on_layout(self, layout=None):
  2748. self.report_usage("on_layout()")
  2749. if layout is None:
  2750. current_layout= self.general_defaults_form.general_gui_group.layout_combo.get_value().lower()
  2751. else:
  2752. current_layout = layout
  2753. settings = QSettings("Open Source", "FlatCAM")
  2754. settings.setValue('layout', current_layout)
  2755. # This will write the setting to the platform specific storage.
  2756. del settings
  2757. # first remove the toolbars:
  2758. self.ui.removeToolBar(self.ui.toolbarfile)
  2759. self.ui.removeToolBar(self.ui.toolbargeo)
  2760. self.ui.removeToolBar(self.ui.toolbarview)
  2761. self.ui.removeToolBar(self.ui.toolbartools)
  2762. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  2763. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  2764. self.ui.removeToolBar(self.ui.snap_toolbar)
  2765. if current_layout == 'standard':
  2766. ### TOOLBAR INSTALLATION ###
  2767. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  2768. self.ui.toolbarfile.setObjectName('File_TB')
  2769. self.ui.addToolBar(self.ui.toolbarfile)
  2770. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  2771. self.ui.toolbargeo.setObjectName('Edit_TB')
  2772. self.ui.addToolBar(self.ui.toolbargeo)
  2773. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  2774. self.ui.toolbarview.setObjectName('View_TB')
  2775. self.ui.addToolBar(self.ui.toolbarview)
  2776. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  2777. self.ui.toolbartools.setObjectName('Tools_TB')
  2778. self.ui.addToolBar(self.ui.toolbartools)
  2779. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  2780. self.ui.exc_edit_toolbar.setVisible(False)
  2781. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  2782. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  2783. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  2784. self.ui.geo_edit_toolbar.setVisible(False)
  2785. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  2786. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  2787. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  2788. self.ui.snap_toolbar.setObjectName('Snap_TB')
  2789. # self.ui.snap_toolbar.setMaximumHeight(30)
  2790. self.ui.addToolBar(self.ui.snap_toolbar)
  2791. self.ui.corner_snap_btn.setVisible(False)
  2792. self.ui.snap_magnet.setVisible(False)
  2793. elif current_layout == 'compact':
  2794. ### TOOLBAR INSTALLATION ###
  2795. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  2796. self.ui.toolbarfile.setObjectName('File_TB')
  2797. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  2798. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  2799. self.ui.toolbargeo.setObjectName('Edit_TB')
  2800. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  2801. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  2802. self.ui.toolbarview.setObjectName('View_TB')
  2803. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  2804. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  2805. self.ui.toolbartools.setObjectName('Tools_TB')
  2806. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  2807. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  2808. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  2809. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.exc_edit_toolbar)
  2810. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  2811. self.ui.geo_edit_toolbar.setVisible(False)
  2812. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  2813. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  2814. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  2815. self.ui.snap_toolbar.setObjectName('Snap_TB')
  2816. self.ui.snap_toolbar.setMaximumHeight(30)
  2817. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  2818. self.ui.corner_snap_btn.setVisible(True)
  2819. self.ui.snap_magnet.setVisible(True)
  2820. self.ui.populate_toolbars()
  2821. self.ui.grid_snap_btn.setChecked(True)
  2822. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  2823. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  2824. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  2825. self.ui.grid_gap_link_cb.setChecked(True)
  2826. def on_save_button(self):
  2827. self.save_defaults(silent=False)
  2828. # load the defaults so they are updated into the app
  2829. self.load_defaults(filename='current_defaults')
  2830. # Re-fresh project options
  2831. self.on_options_app2project()
  2832. def handleOpen(self):
  2833. self.report_usage("handleOpen()")
  2834. filter_group = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2835. "All Files (*.*)"
  2836. path, _ = QtWidgets.QFileDialog.getOpenFileName(
  2837. caption='Open file', directory=self.get_last_folder(), filter=filter_group)
  2838. if path:
  2839. file = QtCore.QFile(path)
  2840. if file.open(QtCore.QIODevice.ReadOnly):
  2841. stream = QtCore.QTextStream(file)
  2842. self.gcode_edited = stream.readAll()
  2843. self.ui.code_editor.setPlainText(self.gcode_edited)
  2844. file.close()
  2845. def handlePrint(self):
  2846. self.report_usage("handlePrint()")
  2847. dialog = QtPrintSupport.QPrintDialog()
  2848. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  2849. self.ui.code_editor.document().print_(dialog.printer())
  2850. def handlePreview(self):
  2851. self.report_usage("handlePreview()")
  2852. dialog = QtPrintSupport.QPrintPreviewDialog()
  2853. dialog.paintRequested.connect(self.ui.code_editor.print_)
  2854. dialog.exec_()
  2855. def handleTextChanged(self):
  2856. self.report_usage("handleTextChanged()")
  2857. # enable = not self.ui.code_editor.document().isEmpty()
  2858. # self.ui.buttonPrint.setEnabled(enable)
  2859. # self.ui.buttonPreview.setEnabled(enable)
  2860. pass
  2861. def handleSaveGCode(self):
  2862. self.report_usage("handleSaveGCode()")
  2863. obj_name = self.collection.get_active().options['name']
  2864. _filter_ = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2865. "All Files (*.*)"
  2866. try:
  2867. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  2868. caption="Export G-Code ...",
  2869. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  2870. filter=_filter_
  2871. )[0])
  2872. except TypeError:
  2873. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption="Export G-Code ...", filter=_filter_)[0])
  2874. if filename == "":
  2875. self.inform.emit("[WARNING_NOTCL]Export CNC Code cancelled.")
  2876. return
  2877. else:
  2878. try:
  2879. my_gcode = self.ui.code_editor.toPlainText()
  2880. with open(filename, 'w') as f:
  2881. for line in my_gcode:
  2882. f.write(line)
  2883. except FileNotFoundError:
  2884. self.inform.emit("[WARNING] No such file or directory")
  2885. return
  2886. # Just for adding it to the recent files list.
  2887. self.file_opened.emit("cncjob", filename)
  2888. self.file_saved.emit("cncjob", filename)
  2889. self.inform.emit("Saved to: " + filename)
  2890. def handleFindGCode(self):
  2891. self.report_usage("handleFindGCode()")
  2892. flags = QtGui.QTextDocument.FindCaseSensitively
  2893. text_to_be_found = self.ui.entryFind.get_value()
  2894. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  2895. if r is False:
  2896. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2897. def handleReplaceGCode(self):
  2898. self.report_usage("handleReplaceGCode()")
  2899. old = self.ui.entryFind.get_value()
  2900. new = self.ui.entryReplace.get_value()
  2901. if self.ui.sel_all_cb.isChecked():
  2902. while True:
  2903. cursor = self.ui.code_editor.textCursor()
  2904. cursor.beginEditBlock()
  2905. flags = QtGui.QTextDocument.FindCaseSensitively
  2906. # self.ui.editor is the QPlainTextEdit
  2907. r = self.ui.code_editor.find(str(old), flags)
  2908. if r:
  2909. qc = self.ui.code_editor.textCursor()
  2910. if qc.hasSelection():
  2911. qc.insertText(new)
  2912. else:
  2913. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2914. break
  2915. # Mark end of undo block
  2916. cursor.endEditBlock()
  2917. else:
  2918. cursor = self.ui.code_editor.textCursor()
  2919. cursor.beginEditBlock()
  2920. qc = self.ui.code_editor.textCursor()
  2921. if qc.hasSelection():
  2922. qc.insertText(new)
  2923. # Mark end of undo block
  2924. cursor.endEditBlock()
  2925. def on_tool_add_keypress(self):
  2926. ## Current application units in Upper Case
  2927. self.units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  2928. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  2929. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  2930. if notebook_widget_name == 'selected_tab':
  2931. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  2932. tool_add_popup = FCInputDialog(title="New Tool ...",
  2933. text='Enter a Tool Diameter:',
  2934. min=0.0000, max=99.9999, decimals=4)
  2935. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  2936. val, ok = tool_add_popup.get_value()
  2937. if ok:
  2938. if float(val) == 0:
  2939. self.inform.emit(
  2940. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  2941. return
  2942. self.collection.get_active().on_tool_add(dia=float(val))
  2943. else:
  2944. self.inform.emit(
  2945. "[WARNING_NOTCL] Adding Tool cancelled ...")
  2946. # work only if the notebook tab on focus is the Tools_Tab
  2947. if notebook_widget_name == 'tool_tab':
  2948. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  2949. # and only if the tool is NCC Tool
  2950. if tool_widget == self.ncclear_tool.toolName:
  2951. tool_add_popup = FCInputDialog(title="New Tool ...",
  2952. text='Enter a Tool Diameter:',
  2953. min=0.0000, max=99.9999, decimals=4)
  2954. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  2955. val, ok = tool_add_popup.get_value()
  2956. if ok:
  2957. if float(val) == 0:
  2958. self.inform.emit(
  2959. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  2960. return
  2961. self.ncclear_tool.on_tool_add(dia=float(val))
  2962. else:
  2963. self.inform.emit(
  2964. "[WARNING_NOTCL] Adding Tool cancelled ...")
  2965. # and only if the tool is Paint Area Tool
  2966. elif tool_widget == self.paint_tool.toolName:
  2967. tool_add_popup = FCInputDialog(title="New Tool ...",
  2968. text='Enter a Tool Diameter:',
  2969. min=0.0000, max=99.9999, decimals=4)
  2970. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  2971. val, ok = tool_add_popup.get_value()
  2972. if ok:
  2973. if float(val) == 0:
  2974. self.inform.emit(
  2975. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  2976. return
  2977. self.paint_tool.on_tool_add(dia=float(val))
  2978. else:
  2979. self.inform.emit(
  2980. "[WARNING_NOTCL] Adding Tool cancelled ...")
  2981. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  2982. # See description bellow.
  2983. def on_delete_keypress(self):
  2984. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  2985. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  2986. if notebook_widget_name == 'selected_tab':
  2987. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  2988. self.collection.get_active().on_tool_delete()
  2989. # work only if the notebook tab on focus is the Tools_Tab
  2990. elif notebook_widget_name == 'tool_tab':
  2991. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  2992. # and only if the tool is NCC Tool
  2993. if tool_widget == self.ncclear_tool.toolName:
  2994. self.ncclear_tool.on_tool_delete()
  2995. # and only if the tool is Paint Tool
  2996. elif tool_widget == self.paint_tool.toolName:
  2997. self.paint_tool.on_tool_delete()
  2998. else:
  2999. self.on_delete()
  3000. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3001. # some screens you have to be careful where you hover with your mouse.
  3002. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3003. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3004. # Complicated, I know :)
  3005. def on_delete(self):
  3006. """
  3007. Delete the currently selected FlatCAMObjs.
  3008. :return: None
  3009. """
  3010. self.report_usage("on_delete()")
  3011. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3012. # a geometry object before we update it.
  3013. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  3014. if self.collection.get_active():
  3015. self.log.debug("on_delete()")
  3016. self.report_usage("on_delete")
  3017. while (self.collection.get_active()):
  3018. self.delete_first_selected()
  3019. self.inform.emit("Object(s) deleted ...")
  3020. # make sure that the selection shape is deleted, too
  3021. self.delete_selection_shape()
  3022. else:
  3023. self.inform.emit("Failed. No object(s) selected...")
  3024. else:
  3025. self.inform.emit("Save the work in Editor and try again ...")
  3026. def on_set_origin(self):
  3027. """
  3028. Set the origin to the left mouse click position
  3029. :return: None
  3030. """
  3031. #display the message for the user
  3032. #and ask him to click on the desired position
  3033. self.report_usage("on_set_origin()")
  3034. self.inform.emit('Click to set the origin ...')
  3035. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  3036. def on_jump_to(self):
  3037. """
  3038. Jump to a location by setting the mouse cursor location
  3039. :return:
  3040. """
  3041. self.report_usage("on_jump_to()")
  3042. dia_box = Dialog_box(title="Jump to ...",
  3043. label="Enter the coordinates in format X,Y:",
  3044. icon=QtGui.QIcon('share/jump_to16.png'))
  3045. if dia_box.ok is True:
  3046. try:
  3047. location = eval(dia_box.location)
  3048. if not isinstance(location, tuple):
  3049. self.inform.emit("Wrong coordinates. Enter coordinates in format: X,Y")
  3050. return
  3051. except:
  3052. return
  3053. else:
  3054. return
  3055. self.plotcanvas.fit_center(loc=location)
  3056. cursor = QtGui.QCursor()
  3057. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3058. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  3059. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  3060. self.inform.emit("Done.")
  3061. def on_copy_object(self):
  3062. self.report_usage("on_copy_object()")
  3063. def initialize(obj_init, app):
  3064. obj_init.solid_geometry = obj.solid_geometry
  3065. try:
  3066. if obj.tools:
  3067. obj_init.tools = obj.tools
  3068. except Exception as e:
  3069. log.debug("on_copy_object() --> %s" % str(e))
  3070. def initialize_excellon(obj_init, app):
  3071. obj_init.tools = obj.tools
  3072. # drills are offset, so they need to be deep copied
  3073. obj_init.drills = deepcopy(obj.drills)
  3074. # slots are offset, so they need to be deep copied
  3075. obj_init.slots = deepcopy(obj.slots)
  3076. obj_init.create_geometry()
  3077. for obj in self.collection.get_selected():
  3078. obj_name = obj.options["name"]
  3079. try:
  3080. if isinstance(obj, FlatCAMExcellon):
  3081. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3082. elif isinstance(obj,FlatCAMGerber):
  3083. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  3084. elif isinstance(obj,FlatCAMGeometry):
  3085. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  3086. except Exception as e:
  3087. return "Operation failed: %s" % str(e)
  3088. def on_copy_object2(self, custom_name):
  3089. def initialize_geometry(obj_init, app):
  3090. obj_init.solid_geometry = obj.solid_geometry
  3091. try:
  3092. if obj.tools:
  3093. obj_init.tools = obj.tools
  3094. except Exception as e:
  3095. log.debug("on_copy_object2() --> %s" % str(e))
  3096. def initialize_gerber(obj_init, app):
  3097. obj_init.solid_geometry = obj.solid_geometry
  3098. obj_init.apertures = deepcopy(obj.apertures)
  3099. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3100. def initialize_excellon(obj_init, app):
  3101. obj_init.tools = obj.tools
  3102. # drills are offset, so they need to be deep copied
  3103. obj_init.drills = deepcopy(obj.drills)
  3104. # slots are offset, so they need to be deep copied
  3105. obj_init.slots = deepcopy(obj.slots)
  3106. obj_init.create_geometry()
  3107. for obj in self.collection.get_selected():
  3108. obj_name = obj.options["name"]
  3109. try:
  3110. if isinstance(obj, FlatCAMExcellon):
  3111. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3112. elif isinstance(obj,FlatCAMGerber):
  3113. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  3114. elif isinstance(obj,FlatCAMGeometry):
  3115. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  3116. except Exception as e:
  3117. return "Operation failed: %s" % str(e)
  3118. def on_rename_object(self, text):
  3119. self.report_usage("on_rename_object()")
  3120. named_obj = self.collection.get_active()
  3121. for obj in named_obj:
  3122. if obj is list:
  3123. self.on_rename_object(text)
  3124. else:
  3125. try:
  3126. obj.options['name'] = text
  3127. except:
  3128. log.warning("Could not rename the object in the list")
  3129. def on_copy_object_as_geometry(self):
  3130. self.report_usage("on_copy_object_as_geometry()")
  3131. def initialize(obj_init, app):
  3132. obj_init.solid_geometry = obj.solid_geometry
  3133. if obj.tools:
  3134. obj_init.tools = obj.tools
  3135. def initialize_excellon(obj, app):
  3136. objs = self.collection.get_selected()
  3137. FlatCAMGeometry.merge(objs, obj)
  3138. for obj in self.collection.get_selected():
  3139. obj_name = obj.options["name"]
  3140. try:
  3141. if isinstance(obj, FlatCAMExcellon):
  3142. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  3143. else:
  3144. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  3145. except Exception as e:
  3146. return "Operation failed: %s" % str(e)
  3147. def on_set_zero_click(self, event):
  3148. #this function will be available only for mouse left click
  3149. pos =[]
  3150. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3151. if event.button == 1:
  3152. if self.grid_status() == True:
  3153. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3154. else:
  3155. pos = pos_canvas
  3156. x = 0 - pos[0]
  3157. y = 0 - pos[1]
  3158. for obj in self.collection.get_list():
  3159. obj.offset((x,y))
  3160. self.object_changed.emit(obj)
  3161. # obj.plot()
  3162. self.plot_all(zoom=False)
  3163. self.inform.emit('[success] Origin set ...')
  3164. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  3165. self.should_we_save = True
  3166. def on_selectall(self):
  3167. self.report_usage("on_selectall()")
  3168. # delete the possible selection box around a possible selected object
  3169. self.delete_selection_shape()
  3170. for name in self.collection.get_names():
  3171. self.collection.set_active(name)
  3172. curr_sel_obj = self.collection.get_by_name(name)
  3173. # create the selection box around the selected object
  3174. self.draw_selection_shape(curr_sel_obj)
  3175. def on_preferences(self):
  3176. # add the tab if it was closed
  3177. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, "Preferences")
  3178. # delete the absolute and relative position and messages in the infobar
  3179. self.ui.position_label.setText("")
  3180. self.ui.rel_position_label.setText("")
  3181. # Switch plot_area to preferences page
  3182. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  3183. self.ui.show()
  3184. def on_flipy(self):
  3185. self.report_usage("on_flipy()")
  3186. obj_list = self.collection.get_selected()
  3187. xminlist = []
  3188. yminlist = []
  3189. xmaxlist = []
  3190. ymaxlist = []
  3191. if not obj_list:
  3192. self.inform.emit("[WARNING_NOTCL] No object selected to Flip on Y axis.")
  3193. else:
  3194. try:
  3195. # first get a bounding box to fit all
  3196. for obj in obj_list:
  3197. xmin, ymin, xmax, ymax = obj.bounds()
  3198. xminlist.append(xmin)
  3199. yminlist.append(ymin)
  3200. xmaxlist.append(xmax)
  3201. ymaxlist.append(ymax)
  3202. # get the minimum x,y and maximum x,y for all objects selected
  3203. xminimal = min(xminlist)
  3204. yminimal = min(yminlist)
  3205. xmaximal = max(xmaxlist)
  3206. ymaximal = max(ymaxlist)
  3207. px = 0.5 * (xminimal + xmaximal)
  3208. py = 0.5 * (yminimal + ymaximal)
  3209. # execute mirroring
  3210. for obj in obj_list:
  3211. obj.mirror('X', [px, py])
  3212. obj.plot()
  3213. self.object_changed.emit(obj)
  3214. except Exception as e:
  3215. self.inform.emit("[ERROR_NOTCL] Due of %s, Flip action was not executed." % str(e))
  3216. return
  3217. def on_flipx(self):
  3218. self.report_usage("on_flipx()")
  3219. obj_list = self.collection.get_selected()
  3220. xminlist = []
  3221. yminlist = []
  3222. xmaxlist = []
  3223. ymaxlist = []
  3224. if not obj_list:
  3225. self.inform.emit("[WARNING_NOTCL] No object selected to Flip on X axis.")
  3226. else:
  3227. try:
  3228. # first get a bounding box to fit all
  3229. for obj in obj_list:
  3230. xmin, ymin, xmax, ymax = obj.bounds()
  3231. xminlist.append(xmin)
  3232. yminlist.append(ymin)
  3233. xmaxlist.append(xmax)
  3234. ymaxlist.append(ymax)
  3235. # get the minimum x,y and maximum x,y for all objects selected
  3236. xminimal = min(xminlist)
  3237. yminimal = min(yminlist)
  3238. xmaximal = max(xmaxlist)
  3239. ymaximal = max(ymaxlist)
  3240. px = 0.5 * (xminimal + xmaximal)
  3241. py = 0.5 * (yminimal + ymaximal)
  3242. # execute mirroring
  3243. for obj in obj_list:
  3244. obj.mirror('Y', [px, py])
  3245. obj.plot()
  3246. self.object_changed.emit(obj)
  3247. except Exception as e:
  3248. self.inform.emit("[ERROR_NOTCL] Due of %s, Flip action was not executed." % str(e))
  3249. return
  3250. def on_rotate(self, silent=False, preset=None):
  3251. self.report_usage("on_rotate()")
  3252. obj_list = self.collection.get_selected()
  3253. xminlist = []
  3254. yminlist = []
  3255. xmaxlist = []
  3256. ymaxlist = []
  3257. if not obj_list:
  3258. self.inform.emit("[WARNING_NOTCL] No object selected to Rotate.")
  3259. else:
  3260. if silent is False:
  3261. rotatebox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3262. min=-360, max=360, decimals=3)
  3263. num, ok = rotatebox.get_value()
  3264. else:
  3265. num = preset
  3266. ok = True
  3267. if ok:
  3268. try:
  3269. # first get a bounding box to fit all
  3270. for obj in obj_list:
  3271. xmin, ymin, xmax, ymax = obj.bounds()
  3272. xminlist.append(xmin)
  3273. yminlist.append(ymin)
  3274. xmaxlist.append(xmax)
  3275. ymaxlist.append(ymax)
  3276. # get the minimum x,y and maximum x,y for all objects selected
  3277. xminimal = min(xminlist)
  3278. yminimal = min(yminlist)
  3279. xmaximal = max(xmaxlist)
  3280. ymaximal = max(ymaxlist)
  3281. px = 0.5 * (xminimal + xmaximal)
  3282. py = 0.5 * (yminimal + ymaximal)
  3283. for sel_obj in obj_list:
  3284. sel_obj.rotate(-num, point=(px, py))
  3285. sel_obj.plot()
  3286. self.object_changed.emit(sel_obj)
  3287. except Exception as e:
  3288. self.inform.emit("[ERROR_NOTCL] Due of %s, rotation movement was not executed." % str(e))
  3289. return
  3290. def on_skewx(self):
  3291. self.report_usage("on_skewx()")
  3292. obj_list = self.collection.get_selected()
  3293. xminlist = []
  3294. yminlist = []
  3295. if not obj_list:
  3296. self.inform.emit("[WARNING_NOTCL] No object selected to Skew/Shear on X axis.")
  3297. else:
  3298. skewxbox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3299. min=-360, max=360, decimals=3)
  3300. num, ok = skewxbox.get_value()
  3301. if ok:
  3302. # first get a bounding box to fit all
  3303. for obj in obj_list:
  3304. xmin, ymin, xmax, ymax = obj.bounds()
  3305. xminlist.append(xmin)
  3306. yminlist.append(ymin)
  3307. # get the minimum x,y and maximum x,y for all objects selected
  3308. xminimal = min(xminlist)
  3309. yminimal = min(yminlist)
  3310. for obj in obj_list:
  3311. obj.skew(num, 0, point=(xminimal, yminimal))
  3312. obj.plot()
  3313. self.object_changed.emit(obj)
  3314. def on_skewy(self):
  3315. self.report_usage("on_skewy()")
  3316. obj_list = self.collection.get_selected()
  3317. xminlist = []
  3318. yminlist = []
  3319. if not obj_list:
  3320. self.inform.emit("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis.")
  3321. else:
  3322. skewybox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3323. min=-360, max=360, decimals=3)
  3324. num, ok = skewybox.get_value()
  3325. if ok:
  3326. # first get a bounding box to fit all
  3327. for obj in obj_list:
  3328. xmin, ymin, xmax, ymax = obj.bounds()
  3329. xminlist.append(xmin)
  3330. yminlist.append(ymin)
  3331. # get the minimum x,y and maximum x,y for all objects selected
  3332. xminimal = min(xminlist)
  3333. yminimal = min(yminlist)
  3334. for obj in obj_list:
  3335. obj.skew(0, num, point=(xminimal, yminimal))
  3336. obj.plot()
  3337. self.object_changed.emit(obj)
  3338. def delete_first_selected(self):
  3339. # Keep this for later
  3340. try:
  3341. name = self.collection.get_active().options["name"]
  3342. except AttributeError:
  3343. self.log.debug("Nothing selected for deletion")
  3344. return
  3345. # Remove plot
  3346. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3347. # self.plotcanvas.auto_adjust_axes()
  3348. # Clear form
  3349. self.setup_component_editor()
  3350. # Remove from dictionary
  3351. self.collection.delete_active()
  3352. self.inform.emit("Object deleted: %s" % name)
  3353. def on_plots_updated(self):
  3354. """
  3355. Callback used to report when the plots have changed.
  3356. Adjust axes and zooms to fit.
  3357. :return: None
  3358. """
  3359. # self.plotcanvas.auto_adjust_axes()
  3360. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  3361. self.on_zoom_fit(None)
  3362. # TODO: Rework toolbar 'clear', 'replot' functions
  3363. def on_toolbar_replot(self):
  3364. """
  3365. Callback for toolbar button. Re-plots all objects.
  3366. :return: None
  3367. """
  3368. self.report_usage("on_toolbar_replot")
  3369. self.log.debug("on_toolbar_replot()")
  3370. try:
  3371. self.collection.get_active().read_form()
  3372. except AttributeError:
  3373. self.log.debug("on_toolbar_replot(): AttributeError")
  3374. pass
  3375. self.plot_all()
  3376. def on_row_activated(self, index):
  3377. if index.isValid():
  3378. if index.internalPointer().parent_item != self.collection.root_item:
  3379. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3380. def grid_status(self):
  3381. if self.ui.grid_snap_btn.isChecked():
  3382. return 1
  3383. else:
  3384. return 0
  3385. def populate_cmenu_grids(self):
  3386. units = self.general_options_form.general_app_group.units_radio.get_value().lower()
  3387. self.ui.cmenu_gridmenu.clear()
  3388. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  3389. for grid in sorted_list:
  3390. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  3391. action.triggered.connect(self.set_grid)
  3392. self.ui.cmenu_gridmenu.addSeparator()
  3393. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), "Add")
  3394. grid_add.triggered.connect(self.on_grid_add)
  3395. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), "Delete")
  3396. grid_delete.triggered.connect(self.on_grid_delete)
  3397. def set_grid(self):
  3398. self.ui.grid_gap_x_entry.setText(self.sender().text())
  3399. self.ui.grid_gap_y_entry.setText(self.sender().text())
  3400. def on_grid_add(self):
  3401. ## Current application units in lower Case
  3402. units = self.general_options_form.general_app_group.units_radio.get_value().lower()
  3403. grid_add_popup = FCInputDialog(title="New Grid ...",
  3404. text='Enter a Grid VAlue:',
  3405. min=0.0000, max=99.9999, decimals=4)
  3406. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  3407. val, ok = grid_add_popup.get_value()
  3408. if ok:
  3409. if float(val) == 0:
  3410. self.inform.emit(
  3411. "[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format.")
  3412. return
  3413. else:
  3414. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  3415. self.defaults["global_grid_context_menu"][str(units)].append(val)
  3416. self.inform.emit(
  3417. "[success] New Grid added ...")
  3418. else:
  3419. self.inform.emit(
  3420. "[WARNING_NOTCL] Grid already exists ...")
  3421. else:
  3422. self.inform.emit(
  3423. "[WARNING_NOTCL] Adding New Grid cancelled ...")
  3424. def on_grid_delete(self):
  3425. ## Current application units in lower Case
  3426. units = self.general_options_form.general_app_group.units_radio.get_value().lower()
  3427. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  3428. text='Enter a Grid Value:',
  3429. min=0.0000, max=99.9999, decimals=4)
  3430. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  3431. val, ok = grid_del_popup.get_value()
  3432. if ok:
  3433. if float(val) == 0:
  3434. self.inform.emit(
  3435. "[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format.")
  3436. return
  3437. else:
  3438. try:
  3439. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  3440. except ValueError:
  3441. self.inform.emit(
  3442. "[ERROR_NOTCL] Grid Value does not exist ...")
  3443. return
  3444. self.inform.emit(
  3445. "[success] Grid Value deleted ...")
  3446. else:
  3447. self.inform.emit(
  3448. "[WARNING_NOTCL] Delete Grid value cancelled ...")
  3449. def on_shortcut_list(self):
  3450. self.report_usage("on_shortcut_list()")
  3451. # add the tab if it was closed
  3452. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  3453. # delete the absolute and relative position and messages in the infobar
  3454. self.ui.position_label.setText("")
  3455. self.ui.rel_position_label.setText("")
  3456. # Switch plot_area to preferences page
  3457. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  3458. self.ui.show()
  3459. def on_select_tab(self, name):
  3460. if name == 'project':
  3461. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3462. elif name == 'selected':
  3463. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3464. elif name == 'tool':
  3465. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  3466. # if the splitter us hidden, display it
  3467. if self.ui.splitter.sizes()[0] == 0:
  3468. self.ui.splitter.setSizes([1, 1])
  3469. def on_copy_name(self):
  3470. self.report_usage("on_copy_name()")
  3471. obj = self.collection.get_active()
  3472. try:
  3473. name = obj.options["name"]
  3474. except AttributeError:
  3475. log.debug("on_copy_name() --> No object selected to copy it's name")
  3476. self.inform.emit("[WARNING_NOTCL]No object selected to copy it's name")
  3477. return
  3478. self.clipboard.setText(name)
  3479. self.inform.emit("Name copied on clipboard ...")
  3480. def on_mouse_click_over_plot(self, event):
  3481. """
  3482. Callback for the mouse click event over the plot. This event is generated
  3483. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3484. For details, see: http://matplotlib.org/users/event_handling.html
  3485. Default actions are:
  3486. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  3487. :param event: Contains information about the event, like which button
  3488. was clicked, the pixel coordinates and the axes coordinates.
  3489. :return: None
  3490. """
  3491. self.pos = []
  3492. # So it can receive key presses
  3493. self.plotcanvas.vispy_canvas.native.setFocus()
  3494. # Set the mouse button for panning
  3495. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  3496. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3497. if self.grid_status() == True:
  3498. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  3499. self.app_cursor.enabled = True
  3500. else:
  3501. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  3502. self.app_cursor.enabled = False
  3503. try:
  3504. # App.log.debug('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  3505. # event.button, event.pos[0], event.pos[1], self.pos[0], self.pos[1]))
  3506. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3507. if event.button == 1:
  3508. # Reset here the relative coordinates so there is a new reference on the click position
  3509. if self.rel_point1 is None:
  3510. self.rel_point1 = self.pos
  3511. else:
  3512. self.rel_point2 = copy(self.rel_point1)
  3513. self.rel_point1 = self.pos
  3514. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3515. if modifiers == QtCore.Qt.ShiftModifier:
  3516. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3517. return
  3518. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  3519. # and if it's not selected then it will be selected
  3520. if modifiers == QtCore.Qt.ControlModifier:
  3521. # If there is no active command (self.command_active is None) then we check if we clicked on
  3522. # a object by checking the bounding limits against mouse click position
  3523. if self.command_active is None:
  3524. self.select_objects(key='CTRL')
  3525. else:
  3526. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  3527. # checking the bounding limits against mouse click position
  3528. if self.command_active is None:
  3529. self.select_objects()
  3530. self.on_mouse_move_over_plot(event, origin_click=True)
  3531. except Exception as e:
  3532. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  3533. def on_double_click_over_plot(self, event):
  3534. # make double click work only for the LMB
  3535. if event.button == 1:
  3536. if self.collection.get_selected():
  3537. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3538. # delete the selection shape(S) as it may be in the way
  3539. self.delete_selection_shape()
  3540. def on_mouse_move_over_plot(self, event, origin_click=None):
  3541. """
  3542. Callback for the mouse motion event over the plot. This event is generated
  3543. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3544. For details, see: http://matplotlib.org/users/event_handling.html
  3545. :param event: Contains information about the event.
  3546. :param origin_click
  3547. :return: None
  3548. """
  3549. # So it can receive key presses
  3550. self.plotcanvas.vispy_canvas.native.setFocus()
  3551. self.pos_jump = event.pos
  3552. if origin_click is True:
  3553. pass
  3554. else:
  3555. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3556. if event.button == 2:
  3557. self.panning_action = True
  3558. return
  3559. else:
  3560. self.panning_action = False
  3561. if self.rel_point1 is not None:
  3562. try: # May fail in case mouse not within axes
  3563. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3564. if self.grid_status():
  3565. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3566. self.app_cursor.enabled = True
  3567. # Update cursor
  3568. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  3569. else:
  3570. pos = (pos_canvas[0], pos_canvas[1])
  3571. self.app_cursor.enabled = False
  3572. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3573. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  3574. dx = pos[0] - self.rel_point1[0]
  3575. dy = pos[1] - self.rel_point1[1]
  3576. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3577. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3578. self.mouse = [pos[0], pos[1]]
  3579. # if the mouse is moved and the LMB is clicked then the action is a selection
  3580. if event.is_dragging == 1 and event.button == 1:
  3581. self.delete_selection_shape()
  3582. if dx < 0:
  3583. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  3584. face_color=self.defaults['global_alt_sel_fill'])
  3585. self.selection_type = False
  3586. else:
  3587. self.draw_moving_selection_shape(self.pos, pos)
  3588. self.selection_type = True
  3589. # delete the status message on mouse move
  3590. # self.inform.emit("")
  3591. except:
  3592. self.ui.position_label.setText("")
  3593. self.ui.rel_position_label.setText("")
  3594. self.mouse = None
  3595. def on_mouse_click_release_over_plot(self, event):
  3596. """
  3597. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  3598. and has been registered in ''self.__init__()''.
  3599. :param event: contains information about the event.
  3600. :return:
  3601. """
  3602. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3603. if self.grid_status():
  3604. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3605. else:
  3606. pos = (pos_canvas[0], pos_canvas[1])
  3607. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3608. # canvas menu
  3609. try:
  3610. if event.button == 2: # right click
  3611. if self.panning_action is True:
  3612. self.panning_action = False
  3613. else:
  3614. self.cursor = QtGui.QCursor()
  3615. self.populate_cmenu_grids()
  3616. self.ui.popMenu.popup(self.cursor.pos())
  3617. except Exception as e:
  3618. log.warning("Error: %s" % str(e))
  3619. return
  3620. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3621. # selection and then select a type of selection ("enclosing" or "touching")
  3622. try:
  3623. if event.button == 1: # left click
  3624. if self.selection_type is not None:
  3625. self.selection_area_handler(self.pos, pos, self.selection_type)
  3626. self.selection_type = None
  3627. except Exception as e:
  3628. log.warning("Error: %s" % str(e))
  3629. return
  3630. def selection_area_handler(self, start_pos, end_pos, sel_type):
  3631. """
  3632. :param start_pos: mouse position when the selection LMB click was done
  3633. :param end_pos: mouse position when the left mouse button is released
  3634. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3635. :return:
  3636. """
  3637. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3638. self.delete_selection_shape()
  3639. for obj in self.collection.get_list():
  3640. try:
  3641. # select the object(s) only if it is enabled (plotted)
  3642. if obj.options['plot']:
  3643. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']), (obj.options['xmax'], obj.options['ymin']),
  3644. (obj.options['xmax'], obj.options['ymax']), (obj.options['xmin'], obj.options['ymax'])])
  3645. if sel_type is True:
  3646. if poly_obj.within(poly_selection):
  3647. # create the selection box around the selected object
  3648. self.draw_selection_shape(obj)
  3649. self.collection.set_active(obj.options['name'])
  3650. else:
  3651. if poly_selection.intersects(poly_obj):
  3652. # create the selection box around the selected object
  3653. self.draw_selection_shape(obj)
  3654. self.collection.set_active(obj.options['name'])
  3655. except:
  3656. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  3657. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  3658. # In this case poly_obj creation (see above) will fail
  3659. pass
  3660. def select_objects(self, key=None):
  3661. # list where we store the overlapped objects under our mouse left click position
  3662. objects_under_the_click_list = []
  3663. # Populate the list with the overlapped objects on the click position
  3664. curr_x, curr_y = self.pos
  3665. for obj in self.all_objects_list:
  3666. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  3667. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  3668. if obj.options['name'] not in objects_under_the_click_list:
  3669. if obj.options['plot']:
  3670. # add objects to the objects_under_the_click list only if the object is plotted
  3671. # (active and not disabled)
  3672. objects_under_the_click_list.append(obj.options['name'])
  3673. try:
  3674. # If there is no element in the overlapped objects list then make everyone inactive
  3675. # because we selected "nothing"
  3676. if not objects_under_the_click_list:
  3677. self.collection.set_all_inactive()
  3678. # delete the possible selection box around a possible selected object
  3679. self.delete_selection_shape()
  3680. # and as a convenience move the focus to the Project tab because Selected tab is now empty
  3681. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3682. # delete any text in the status bar, implicitly the last object name that was selected
  3683. self.inform.emit("")
  3684. else:
  3685. # case when there is only an object under the click and we toggle it
  3686. if len(objects_under_the_click_list) == 1:
  3687. if self.collection.get_active() is None :
  3688. self.collection.set_active(objects_under_the_click_list[0])
  3689. # create the selection box around the selected object
  3690. curr_sel_obj = self.collection.get_active()
  3691. self.draw_selection_shape(curr_sel_obj)
  3692. # self.inform.emit('[selected] %s: %s selected' %
  3693. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3694. if curr_sel_obj.kind == 'gerber':
  3695. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3696. ('green', str(curr_sel_obj.options['name'])))
  3697. elif curr_sel_obj.kind == 'excellon':
  3698. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3699. ('brown', str(curr_sel_obj.options['name'])))
  3700. elif curr_sel_obj.kind == 'cncjob':
  3701. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3702. ('blue', str(curr_sel_obj.options['name'])))
  3703. elif curr_sel_obj.kind == 'geometry':
  3704. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3705. ('red', str(curr_sel_obj.options['name'])))
  3706. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  3707. self.collection.set_all_inactive()
  3708. self.delete_selection_shape()
  3709. self.collection.set_active(objects_under_the_click_list[0])
  3710. # create the selection box around the selected object
  3711. curr_sel_obj = self.collection.get_active()
  3712. self.draw_selection_shape(curr_sel_obj)
  3713. # self.inform.emit('[selected] %s: %s selected' %
  3714. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3715. if curr_sel_obj.kind == 'gerber':
  3716. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3717. ('green', str(curr_sel_obj.options['name'])))
  3718. elif curr_sel_obj.kind == 'excellon':
  3719. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3720. ('brown', str(curr_sel_obj.options['name'])))
  3721. elif curr_sel_obj.kind == 'cncjob':
  3722. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3723. ('blue', str(curr_sel_obj.options['name'])))
  3724. elif curr_sel_obj.kind == 'geometry':
  3725. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3726. ('red', str(curr_sel_obj.options['name'])))
  3727. else:
  3728. self.collection.set_all_inactive()
  3729. self.delete_selection_shape()
  3730. self.inform.emit("")
  3731. else:
  3732. # If there is no selected object
  3733. # make active the first element of the overlapped objects list
  3734. if self.collection.get_active() is None:
  3735. self.collection.set_active(objects_under_the_click_list[0])
  3736. name_sel_obj = self.collection.get_active().options['name']
  3737. # In case that there is a selected object but it is not in the overlapped object list
  3738. # make that object inactive and activate the first element in the overlapped object list
  3739. if name_sel_obj not in objects_under_the_click_list:
  3740. self.collection.set_inactive(name_sel_obj)
  3741. name_sel_obj = objects_under_the_click_list[0]
  3742. self.collection.set_active(name_sel_obj)
  3743. else:
  3744. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  3745. self.collection.set_all_inactive()
  3746. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  3747. len(objects_under_the_click_list)])
  3748. curr_sel_obj = self.collection.get_active()
  3749. # delete the possible selection box around a possible selected object
  3750. self.delete_selection_shape()
  3751. # create the selection box around the selected object
  3752. self.draw_selection_shape(curr_sel_obj)
  3753. # self.inform.emit('[selected] %s: %s selected' %
  3754. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3755. if curr_sel_obj.kind == 'gerber':
  3756. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3757. ('green', str(curr_sel_obj.options['name'])))
  3758. elif curr_sel_obj.kind == 'excellon':
  3759. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3760. ('brown', str(curr_sel_obj.options['name'])))
  3761. elif curr_sel_obj.kind == 'cncjob':
  3762. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3763. ('blue', str(curr_sel_obj.options['name'])))
  3764. elif curr_sel_obj.kind == 'geometry':
  3765. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3766. ('red', str(curr_sel_obj.options['name'])))
  3767. # for obj in self.collection.get_list():
  3768. # obj.plot()
  3769. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  3770. # TODO: on selected objects change the object colors and do not draw the selection box
  3771. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  3772. except Exception as e:
  3773. log.error("[ERROR] Something went bad. %s" % str(e))
  3774. return
  3775. def delete_selection_shape(self):
  3776. self.move_tool.sel_shapes.clear()
  3777. self.move_tool.sel_shapes.redraw()
  3778. def draw_selection_shape(self, sel_obj):
  3779. """
  3780. :param sel_obj: the object for which the selection shape must be drawn
  3781. :return:
  3782. """
  3783. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  3784. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  3785. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  3786. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  3787. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3788. #blue_t = Color('blue')
  3789. blue_t = Color(self.defaults['global_sel_fill'])
  3790. blue_t.alpha = 0.3
  3791. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=self.defaults['global_sel_line'],
  3792. face_color=blue_t, update=True, layer=0, tolerance=None))
  3793. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  3794. """
  3795. :param old_coords: old coordinates
  3796. :param coords: new coordinates
  3797. :return:
  3798. """
  3799. if 'color' in kwargs:
  3800. color = kwargs['color']
  3801. else:
  3802. color = self.defaults['global_sel_line']
  3803. if 'face_color' in kwargs:
  3804. face_color = kwargs['face_color']
  3805. else:
  3806. face_color = self.defaults['global_sel_fill']
  3807. x0, y0 = old_coords
  3808. x1, y1 = coords
  3809. pt1 = (x0, y0)
  3810. pt2 = (x1, y0)
  3811. pt3 = (x1, y1)
  3812. pt4 = (x0, y1)
  3813. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3814. color_t = Color(face_color)
  3815. color_t.alpha = 0.3
  3816. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  3817. layer=0, tolerance=None)
  3818. def on_file_new_click(self):
  3819. if self.collection.get_list() and self.should_we_save:
  3820. msgbox = QtWidgets.QMessageBox()
  3821. # msgbox.setText("<B>Save changes ...</B>")
  3822. msgbox.setText("There are files/objects opened in FlatCAM.\n"
  3823. "Creating a New project will delete them.\n"
  3824. "Do you want to Save the project?")
  3825. msgbox.setWindowTitle("Save changes")
  3826. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3827. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Yes |
  3828. QtWidgets.QMessageBox.No)
  3829. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3830. response = msgbox.exec_()
  3831. if response == QtWidgets.QMessageBox.Yes:
  3832. self.on_file_saveprojectas()
  3833. elif response == QtWidgets.QMessageBox.Cancel:
  3834. return
  3835. self.on_file_new()
  3836. else:
  3837. self.on_file_new()
  3838. self.inform.emit("[success] New Project created...")
  3839. def on_file_new(self):
  3840. """
  3841. Callback for menu item File->New. Returns the application to its
  3842. startup state. This method is thread-safe.
  3843. :return: None
  3844. """
  3845. self.report_usage("on_file_new")
  3846. # Remove everything from memory
  3847. App.log.debug("on_file_new()")
  3848. # Clear pool
  3849. self.clear_pool()
  3850. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  3851. self.init_tcl()
  3852. self.delete_selection_shape()
  3853. self.collection.delete_all()
  3854. self.setup_component_editor()
  3855. # Clear project filename
  3856. self.project_filename = None
  3857. # Load the application defaults
  3858. self.load_defaults(filename='current_defaults')
  3859. # Re-fresh project options
  3860. self.on_options_app2project()
  3861. # Init Tools
  3862. self.init_tools()
  3863. # take the focus of the Notebook on Project Tab.
  3864. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3865. def obj_properties(self):
  3866. self.report_usage("obj_properties()")
  3867. self.properties_tool.run()
  3868. def on_project_context_save(self):
  3869. obj = self.collection.get_active()
  3870. if type(obj) == FlatCAMGeometry:
  3871. self.on_file_exportdxf()
  3872. elif type(obj) == FlatCAMExcellon:
  3873. self.on_file_exportexcellon()
  3874. elif type(obj) == FlatCAMCNCjob:
  3875. obj.on_exportgcode_button_click()
  3876. def obj_move(self):
  3877. self.report_usage("obj_move()")
  3878. self.move_tool.run()
  3879. def on_fileopengerber(self):
  3880. """
  3881. File menu callback for opening a Gerber.
  3882. :return: None
  3883. """
  3884. self.report_usage("on_fileopengerber")
  3885. App.log.debug("on_fileopengerber()")
  3886. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3887. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3888. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3889. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3890. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3891. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3892. "Allegro Files (*.art);;" \
  3893. "Mentor Files (*.pho *.gdo);;" \
  3894. "All Files (*.*)"
  3895. try:
  3896. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber",
  3897. directory=self.get_last_folder(), filter=_filter_)
  3898. except TypeError:
  3899. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber", filter=_filter_)
  3900. filenames = [str(filename) for filename in filenames]
  3901. if len(filenames) == 0:
  3902. self.inform.emit("[WARNING_NOTCL]Open Gerber cancelled.")
  3903. else:
  3904. for filename in filenames:
  3905. if filename != '':
  3906. self.worker_task.emit({'fcn': self.open_gerber,
  3907. 'params': [filename]})
  3908. def on_fileopengerber_follow(self):
  3909. """
  3910. File menu callback for opening a Gerber.
  3911. :return: None
  3912. """
  3913. self.report_usage("on_fileopengerber_follow")
  3914. App.log.debug("on_fileopengerber_follow()")
  3915. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3916. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3917. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3918. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3919. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3920. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3921. "Allegro Files (*.art);;" \
  3922. "Mentor Files (*.pho *.gdo);;" \
  3923. "All Files (*.*)"
  3924. try:
  3925. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow",
  3926. directory=self.get_last_folder(), filter=_filter_)
  3927. except TypeError:
  3928. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow", filter=_filter_)
  3929. # The Qt methods above will return a QString which can cause problems later.
  3930. # So far json.dump() will fail to serialize it.
  3931. # TODO: Improve the serialization methods and remove this fix.
  3932. filename = str(filename)
  3933. follow = True
  3934. if filename == "":
  3935. self.inform.emit("[WARNING_NOTCL]Open Gerber-Follow cancelled.")
  3936. else:
  3937. self.worker_task.emit({'fcn': self.open_gerber,
  3938. 'params': [filename, follow]})
  3939. def on_fileopenexcellon(self):
  3940. """
  3941. File menu callback for opening an Excellon file.
  3942. :return: None
  3943. """
  3944. self.report_usage("on_fileopenexcellon")
  3945. App.log.debug("on_fileopenexcellon()")
  3946. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  3947. "All Files (*.*)"
  3948. try:
  3949. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon",
  3950. directory=self.get_last_folder(), filter=_filter_)
  3951. except TypeError:
  3952. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon", filter=_filter_)
  3953. filenames = [str(filename) for filename in filenames]
  3954. if len(filenames) == 0:
  3955. self.inform.emit("[WARNING_NOTCL]Open Excellon cancelled.")
  3956. else:
  3957. for filename in filenames:
  3958. if filename != '':
  3959. self.worker_task.emit({'fcn': self.open_excellon,
  3960. 'params': [filename]})
  3961. def on_fileopengcode(self):
  3962. """
  3963. File menu call back for opening gcode.
  3964. :return: None
  3965. """
  3966. self.report_usage("on_fileopengcode")
  3967. App.log.debug("on_fileopengcode()")
  3968. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  3969. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  3970. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  3971. "All Files (*.*)"
  3972. try:
  3973. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code",
  3974. directory=self.get_last_folder(), filter=_filter_)
  3975. except TypeError:
  3976. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code", filter=_filter_)
  3977. filenames = [str(filename) for filename in filenames]
  3978. if len(filenames) == 0:
  3979. self.inform.emit("[WARNING_NOTCL]Open G-Code cancelled.")
  3980. else:
  3981. for filename in filenames:
  3982. if filename != '':
  3983. self.worker_task.emit({'fcn': self.open_gcode,
  3984. 'params': [filename]})
  3985. def on_file_openproject(self):
  3986. """
  3987. File menu callback for opening a project.
  3988. :return: None
  3989. """
  3990. self.report_usage("on_file_openproject")
  3991. App.log.debug("on_file_openproject()")
  3992. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  3993. try:
  3994. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project",
  3995. directory=self.get_last_folder(), filter=_filter_)
  3996. except TypeError:
  3997. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project", filter = _filter_)
  3998. # The Qt methods above will return a QString which can cause problems later.
  3999. # So far json.dump() will fail to serialize it.
  4000. # TODO: Improve the serialization methods and remove this fix.
  4001. filename = str(filename)
  4002. if filename == "":
  4003. self.inform.emit("[WARNING_NOTCL]Open Project cancelled.")
  4004. else:
  4005. # self.worker_task.emit({'fcn': self.open_project,
  4006. # 'params': [filename]})
  4007. # The above was failing because open_project() is not
  4008. # thread safe. The new_project()
  4009. self.open_project(filename)
  4010. def on_file_exportsvg(self):
  4011. """
  4012. Callback for menu item File->Export SVG.
  4013. :return: None
  4014. """
  4015. self.report_usage("on_file_exportsvg")
  4016. App.log.debug("on_file_exportsvg()")
  4017. obj = self.collection.get_active()
  4018. if obj is None:
  4019. self.inform.emit("WARNING: No object selected.")
  4020. msg = "Please Select a Geometry object to export"
  4021. msgbox = QtWidgets.QMessageBox()
  4022. msgbox.setInformativeText(msg)
  4023. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4024. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4025. msgbox.exec_()
  4026. return
  4027. # Check for more compatible types and add as required
  4028. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  4029. and not isinstance(obj, FlatCAMExcellon)):
  4030. msg = "[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used."
  4031. msgbox = QtWidgets.QMessageBox()
  4032. msgbox.setInformativeText(msg)
  4033. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4034. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4035. msgbox.exec_()
  4036. return
  4037. name = self.collection.get_active().options["name"]
  4038. filter = "SVG File (*.svg);;All Files (*.*)"
  4039. try:
  4040. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4041. caption="Export SVG",
  4042. directory=self.get_last_save_folder() + '/' + str(name),
  4043. filter=filter)
  4044. except TypeError:
  4045. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG", filter=filter)
  4046. filename = str(filename)
  4047. if filename == "":
  4048. self.inform.emit("[WARNING_NOTCL]Export SVG cancelled.")
  4049. return
  4050. else:
  4051. self.export_svg(name, filename)
  4052. self.file_saved.emit("SVG", filename)
  4053. def on_file_exportpng(self):
  4054. self.report_usage("on_file_exportpng")
  4055. App.log.debug("on_file_exportpng()")
  4056. image = _screenshot()
  4057. data = np.asarray(image)
  4058. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  4059. self.inform.emit('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4')
  4060. return
  4061. filter_ = "PNG File (*.png);;All Files (*.*)"
  4062. try:
  4063. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4064. caption="Export PNG Image",
  4065. directory=self.get_last_save_folder() + '/png_' + str(self.date).replace('-', ''),
  4066. filter=filter_)
  4067. except TypeError:
  4068. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image", filter=filter_)
  4069. filename = str(filename)
  4070. if filename == "":
  4071. self.inform.emit("Export PNG cancelled.")
  4072. return
  4073. else:
  4074. write_png(filename, data)
  4075. self.file_saved.emit("png", filename)
  4076. def on_file_exportexcellon(self):
  4077. """
  4078. Callback for menu item File->Export SVG.
  4079. :return: None
  4080. """
  4081. self.report_usage("on_file_exportexcellon")
  4082. App.log.debug("on_file_exportexcellon()")
  4083. obj = self.collection.get_active()
  4084. if obj is None:
  4085. self.inform.emit("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export.")
  4086. return
  4087. # Check for more compatible types and add as required
  4088. if not isinstance(obj, FlatCAMExcellon):
  4089. self.inform.emit("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files...")
  4090. return
  4091. name = self.collection.get_active().options["name"]
  4092. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  4093. try:
  4094. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4095. caption="Export Excellon",
  4096. directory=self.get_last_save_folder() + '/' + name,
  4097. filter=filter)
  4098. except TypeError:
  4099. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon", filter=filter)
  4100. filename = str(filename)
  4101. if filename == "":
  4102. self.inform.emit("[WARNING_NOTCL]Export Excellon cancelled.")
  4103. return
  4104. else:
  4105. self.export_excellon(name, filename)
  4106. self.file_saved.emit("Excellon", filename)
  4107. def on_file_exportdxf(self):
  4108. """
  4109. Callback for menu item File->Export DXF.
  4110. :return: None
  4111. """
  4112. self.report_usage("on_file_exportdxf")
  4113. App.log.debug("on_file_exportdxf()")
  4114. obj = self.collection.get_active()
  4115. if obj is None:
  4116. self.inform.emit("W[WARNING_NOTCL] No object selected.")
  4117. msg = "Please Select a Geometry object to export"
  4118. msgbox = QtWidgets.QMessageBox()
  4119. msgbox.setInformativeText(msg)
  4120. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4121. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4122. msgbox.exec_()
  4123. return
  4124. # Check for more compatible types and add as required
  4125. if not isinstance(obj, FlatCAMGeometry):
  4126. msg = "[ERROR_NOTCL] Only Geometry objects can be used."
  4127. msgbox = QtWidgets.QMessageBox()
  4128. msgbox.setInformativeText(msg)
  4129. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4130. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4131. msgbox.exec_()
  4132. return
  4133. name = self.collection.get_active().options["name"]
  4134. filter = "DXF File (*.DXF);;All Files (*.*)"
  4135. try:
  4136. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4137. caption="Export DXF",
  4138. directory=self.get_last_save_folder() + '/' + name,
  4139. filter=filter)
  4140. except TypeError:
  4141. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF", filter=filter)
  4142. filename = str(filename)
  4143. if filename == "":
  4144. self.inform.emit("[WARNING_NOTCL]Export DXF cancelled.")
  4145. return
  4146. else:
  4147. self.export_dxf(name, filename)
  4148. self.file_saved.emit("DXF", filename)
  4149. def on_file_importsvg(self, type_of_obj):
  4150. """
  4151. Callback for menu item File->Import SVG.
  4152. :param type_of_obj: to import the SVG as Geometry or as Gerber
  4153. :type type_of_obj: str
  4154. :return: None
  4155. """
  4156. self.report_usage("on_file_importsvg")
  4157. App.log.debug("on_file_importsvg()")
  4158. filter = "SVG File (*.svg);;All Files (*.*)"
  4159. try:
  4160. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG",
  4161. directory=self.get_last_folder(), filter=filter)
  4162. except TypeError:
  4163. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG", filter=filter)
  4164. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4165. type_of_obj = "geometry"
  4166. filenames = [str(filename) for filename in filenames]
  4167. if len(filenames) == 0:
  4168. self.inform.emit("[WARNING_NOTCL]Open SVG cancelled.")
  4169. else:
  4170. for filename in filenames:
  4171. if filename != '':
  4172. self.worker_task.emit({'fcn': self.import_svg,
  4173. 'params': [filename, type_of_obj]})
  4174. def on_file_importdxf(self, type_of_obj):
  4175. """
  4176. Callback for menu item File->Import DXF.
  4177. :param type_of_obj: to import the DXF as Geometry or as Gerber
  4178. :type type_of_obj: str
  4179. :return: None
  4180. """
  4181. self.report_usage("on_file_importdxf")
  4182. App.log.debug("on_file_importdxf()")
  4183. filter = "DXF File (*.DXF);;All Files (*.*)"
  4184. try:
  4185. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF",
  4186. directory=self.get_last_folder(), filter=filter)
  4187. except TypeError:
  4188. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF", filter=filter)
  4189. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4190. type_of_obj = "geometry"
  4191. filenames = [str(filename) for filename in filenames]
  4192. if len(filenames) == 0:
  4193. self.inform.emit("[WARNING_NOTCL]Open DXF cancelled.")
  4194. else:
  4195. for filename in filenames:
  4196. if filename != '':
  4197. self.worker_task.emit({'fcn': self.import_dxf,
  4198. 'params': [filename, type_of_obj]})
  4199. def on_filerunscript(self):
  4200. """
  4201. File menu callback for loading and running a TCL script.
  4202. :return: None
  4203. """
  4204. self.report_usage("on_filerunscript")
  4205. App.log.debug("on_file_runscript()")
  4206. _filter_ = "TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  4207. try:
  4208. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script",
  4209. directory=self.get_last_folder(), filter=_filter_)
  4210. except TypeError:
  4211. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script", filter=_filter_)
  4212. # The Qt methods above will return a QString which can cause problems later.
  4213. # So far json.dump() will fail to serialize it.
  4214. # TODO: Improve the serialization methods and remove this fix.
  4215. filename = str(filename)
  4216. if filename == "":
  4217. self.inform.emit("[WARNING_NOTCL]Open TCL script cancelled.")
  4218. else:
  4219. try:
  4220. with open(filename, "r") as tcl_script:
  4221. cmd_line_shellfile_content = tcl_script.read()
  4222. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  4223. except Exception as ext:
  4224. print("ERROR: ", ext)
  4225. sys.exit(2)
  4226. def on_file_saveproject(self):
  4227. """
  4228. Callback for menu item File->Save Project. Saves the project to
  4229. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  4230. if set to None. The project is saved by calling ``self.save_project()``.
  4231. :return: None
  4232. """
  4233. self.report_usage("on_file_saveproject")
  4234. if self.project_filename is None:
  4235. self.on_file_saveprojectas()
  4236. else:
  4237. self.worker_task.emit({'fcn': self.save_project,
  4238. 'params': [self.project_filename]})
  4239. # self.save_project(self.project_filename)
  4240. self.file_opened.emit("project", self.project_filename)
  4241. self.file_saved.emit("project", self.project_filename)
  4242. self.should_we_save = False
  4243. def on_file_saveprojectas(self, make_copy=False, thread=True):
  4244. """
  4245. Callback for menu item File->Save Project As... Opens a file
  4246. chooser and saves the project to the given file via
  4247. ``self.save_project()``.
  4248. :return: None
  4249. """
  4250. self.report_usage("on_file_saveprojectas")
  4251. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  4252. try:
  4253. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4254. caption="Save Project As ...",
  4255. directory=self.get_last_save_folder() + '/Project_' + self.date.replace('-', ''),
  4256. filter=filter_)
  4257. except TypeError:
  4258. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...", filter=filter_)
  4259. filename = str(filename)
  4260. if filename == '':
  4261. self.inform.emit("[WARNING_NOTCL]Save Project cancelled.")
  4262. return
  4263. try:
  4264. f = open(filename, 'r')
  4265. f.close()
  4266. exists = True
  4267. except IOError:
  4268. exists = False
  4269. msg = "Project file exists. Overwrite?"
  4270. if exists:
  4271. msgbox = QtWidgets.QMessageBox()
  4272. msgbox.setInformativeText(msg)
  4273. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel |QtWidgets.QMessageBox.Ok)
  4274. msgbox.setDefaultButton(QtWidgets.QMessageBox.Cancel)
  4275. result = msgbox.exec_()
  4276. if result ==QtWidgets.QMessageBox.Cancel:
  4277. return
  4278. if thread is True:
  4279. self.worker_task.emit({'fcn': self.save_project,
  4280. 'params': [filename]})
  4281. else:
  4282. self.save_project(filename)
  4283. # self.save_project(filename)
  4284. self.file_opened.emit("project", filename)
  4285. self.file_saved.emit("project", filename)
  4286. if not make_copy:
  4287. self.project_filename = filename
  4288. self.should_we_save = False
  4289. def export_svg(self, obj_name, filename, scale_factor=0.00):
  4290. """
  4291. Exports a Geometry Object to an SVG file.
  4292. :param filename: Path to the SVG file to save to.
  4293. :return:
  4294. """
  4295. self.report_usage("export_svg()")
  4296. if filename is None:
  4297. filename = self.defaults["global_last_save_folder"]
  4298. self.log.debug("export_svg()")
  4299. try:
  4300. obj = self.collection.get_by_name(str(obj_name))
  4301. except:
  4302. # TODO: The return behavior has not been established... should raise exception?
  4303. return "Could not retrieve object: %s" % obj_name
  4304. with self.proc_container.new("Exporting SVG") as proc:
  4305. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4306. # Determine bounding area for svg export
  4307. bounds = obj.bounds()
  4308. size = obj.size()
  4309. # Convert everything to strings for use in the xml doc
  4310. svgwidth = str(size[0])
  4311. svgheight = str(size[1])
  4312. minx = str(bounds[0])
  4313. miny = str(bounds[1] - size[1])
  4314. uom = obj.units.lower()
  4315. # Add a SVG Header and footer to the svg output from shapely
  4316. # The transform flips the Y Axis so that everything renders
  4317. # properly within svg apps such as inkscape
  4318. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4319. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4320. svg_header += 'width="' + svgwidth + uom + '" '
  4321. svg_header += 'height="' + svgheight + uom + '" '
  4322. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  4323. svg_header += '<g transform="scale(1,-1)">'
  4324. svg_footer = '</g> </svg>'
  4325. svg_elem = svg_header + exported_svg + svg_footer
  4326. # Parse the xml through a xml parser just to add line feeds
  4327. # and to make it look more pretty for the output
  4328. svgcode = parse_xml_string(svg_elem)
  4329. with open(filename, 'w') as fp:
  4330. fp.write(svgcode.toprettyxml())
  4331. self.file_saved.emit("SVG", filename)
  4332. self.inform.emit("[success] SVG file exported to " + filename)
  4333. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  4334. """
  4335. Exports a Geometry Object to an SVG file in negative.
  4336. :param filename: Path to the SVG file to save to.
  4337. :param: use_thread: If True use threads
  4338. :type: Bool
  4339. :return:
  4340. """
  4341. self.report_usage("export_negative()")
  4342. if filename is None:
  4343. filename = self.defaults["global_last_save_folder"]
  4344. self.log.debug("export_svg() negative")
  4345. try:
  4346. obj = self.collection.get_by_name(str(obj_name))
  4347. except:
  4348. # TODO: The return behavior has not been established... should raise exception?
  4349. return "Could not retrieve object: %s" % obj_name
  4350. try:
  4351. box = self.collection.get_by_name(str(box_name))
  4352. except:
  4353. # TODO: The return behavior has not been established... should raise exception?
  4354. return "Could not retrieve object: %s" % box_name
  4355. if box is None:
  4356. self.inform.emit("[WARNING_NOTCL]No object Box. Using instead %s" % obj)
  4357. box = obj
  4358. def make_negative_film():
  4359. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4360. self.progress.emit(40)
  4361. # Determine bounding area for svg export
  4362. bounds = box.bounds()
  4363. size = box.size()
  4364. uom = obj.units.lower()
  4365. # Convert everything to strings for use in the xml doc
  4366. svgwidth = str(size[0] + (2 * boundary))
  4367. svgheight = str(size[1] + (2 * boundary))
  4368. minx = str(bounds[0] - boundary)
  4369. miny = str(bounds[1] + boundary + size[1])
  4370. miny_rect = str(bounds[1] - boundary)
  4371. # Add a SVG Header and footer to the svg output from shapely
  4372. # The transform flips the Y Axis so that everything renders
  4373. # properly within svg apps such as inkscape
  4374. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4375. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4376. svg_header += 'width="' + svgwidth + uom + '" '
  4377. svg_header += 'height="' + svgheight + uom + '" '
  4378. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4379. svg_header += '>'
  4380. svg_header += '<g transform="scale(1,-1)">'
  4381. svg_footer = '</g> </svg>'
  4382. self.progress.emit(60)
  4383. # Change the attributes of the exported SVG
  4384. # We don't need stroke-width - wrong, we do when we have lines with certain width
  4385. # We set opacity to maximum
  4386. # We set the color to WHITE
  4387. root = ET.fromstring(exported_svg)
  4388. for child in root:
  4389. child.set('fill', '#FFFFFF')
  4390. child.set('opacity', '1.0')
  4391. child.set('stroke', '#FFFFFF')
  4392. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  4393. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  4394. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  4395. first_svg_elem_tag = 'rect'
  4396. first_svg_elem_attribs = {
  4397. 'x': minx,
  4398. 'y': miny_rect,
  4399. 'width': svgwidth,
  4400. 'height': svgheight,
  4401. 'id': 'neg_rect',
  4402. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  4403. }
  4404. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  4405. exported_svg = ET.tostring(root)
  4406. svg_elem = svg_header + str(exported_svg) + svg_footer
  4407. self.progress.emit(80)
  4408. # Parse the xml through a xml parser just to add line feeds
  4409. # and to make it look more pretty for the output
  4410. doc = parse_xml_string(svg_elem)
  4411. with open(filename, 'w') as fp:
  4412. fp.write(doc.toprettyxml())
  4413. self.progress.emit(100)
  4414. self.file_saved.emit("SVG", filename)
  4415. self.inform.emit("[success] SVG file exported to " + filename)
  4416. if use_thread is True:
  4417. proc = self.proc_container.new("Generating Film ... Please wait.")
  4418. def job_thread_film(app_obj):
  4419. try:
  4420. make_negative_film()
  4421. except Exception as e:
  4422. proc.done()
  4423. return
  4424. proc.done()
  4425. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4426. else:
  4427. make_negative_film()
  4428. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  4429. """
  4430. Exports a Geometry Object to an SVG file in negative.
  4431. :param filename: Path to the SVG file to save to.
  4432. :param: use_thread: If True use threads
  4433. :type: Bool
  4434. :return:
  4435. """
  4436. self.report_usage("export_svg_black()")
  4437. if filename is None:
  4438. filename = self.defaults["global_last_save_folder"]
  4439. self.log.debug("export_svg() black")
  4440. try:
  4441. obj = self.collection.get_by_name(str(obj_name))
  4442. except:
  4443. # TODO: The return behavior has not been established... should raise exception?
  4444. return "Could not retrieve object: %s" % obj_name
  4445. try:
  4446. box = self.collection.get_by_name(str(box_name))
  4447. except:
  4448. # TODO: The return behavior has not been established... should raise exception?
  4449. return "Could not retrieve object: %s" % box_name
  4450. if box is None:
  4451. self.inform.emit("[WARNING_NOTCL]No object Box. Using instead %s" % obj)
  4452. box = obj
  4453. def make_black_film():
  4454. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4455. self.progress.emit(40)
  4456. # Change the attributes of the exported SVG
  4457. # We don't need stroke-width
  4458. # We set opacity to maximum
  4459. # We set the colour to WHITE
  4460. root = ET.fromstring(exported_svg)
  4461. for child in root:
  4462. child.set('fill', '#000000')
  4463. child.set('opacity', '1.0')
  4464. child.set('stroke', '#000000')
  4465. exported_svg = ET.tostring(root)
  4466. # Determine bounding area for svg export
  4467. bounds = box.bounds()
  4468. size = box.size()
  4469. # This contain the measure units
  4470. uom = obj.units.lower()
  4471. # Define a boundary around SVG of about 1.0mm (~39mils)
  4472. if uom in "mm":
  4473. boundary = 1.0
  4474. else:
  4475. boundary = 0.0393701
  4476. self.progress.emit(80)
  4477. # Convert everything to strings for use in the xml doc
  4478. svgwidth = str(size[0] + (2 * boundary))
  4479. svgheight = str(size[1] + (2 * boundary))
  4480. minx = str(bounds[0] - boundary)
  4481. miny = str(bounds[1] + boundary + size[1])
  4482. self.log.debug(minx)
  4483. self.log.debug(miny)
  4484. # Add a SVG Header and footer to the svg output from shapely
  4485. # The transform flips the Y Axis so that everything renders
  4486. # properly within svg apps such as inkscape
  4487. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4488. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4489. svg_header += 'width="' + svgwidth + uom + '" '
  4490. svg_header += 'height="' + svgheight + uom + '" '
  4491. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4492. svg_header += '>'
  4493. svg_header += '<g transform="scale(1,-1)">'
  4494. svg_footer = '</g> </svg>'
  4495. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  4496. self.progress.emit(90)
  4497. # Parse the xml through a xml parser just to add line feeds
  4498. # and to make it look more pretty for the output
  4499. doc = parse_xml_string(svg_elem)
  4500. with open(filename, 'w') as fp:
  4501. fp.write(doc.toprettyxml())
  4502. self.progress.emit(100)
  4503. self.file_saved.emit("SVG", filename)
  4504. self.inform.emit("[success] SVG file exported to " + filename)
  4505. if use_thread is True:
  4506. proc = self.proc_container.new("Generating Film ... Please wait.")
  4507. def job_thread_film(app_obj):
  4508. try:
  4509. make_black_film()
  4510. except Exception as e:
  4511. proc.done()
  4512. return
  4513. proc.done()
  4514. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4515. else:
  4516. make_black_film()
  4517. def export_excellon(self, obj_name, filename, use_thread=True):
  4518. """
  4519. Exports a Geometry Object to an Excellon file.
  4520. :param filename: Path to the Excellon file to save to.
  4521. :return:
  4522. """
  4523. self.report_usage("export_excellon()")
  4524. if filename is None:
  4525. filename = self.defaults["global_last_save_folder"]
  4526. self.log.debug("export_excellon()")
  4527. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  4528. self.defaults["excellon_exp_decimals"]
  4529. )
  4530. units = ''
  4531. try:
  4532. obj = self.collection.get_by_name(str(obj_name))
  4533. except:
  4534. # TODO: The return behavior has not been established... should raise exception?
  4535. return "Could not retrieve object: %s" % obj_name
  4536. # updated units
  4537. eunits = self.defaults["excellon_exp_units"]
  4538. ewhole = self.defaults["excellon_exp_integer"]
  4539. efract = self.defaults["excellon_exp_decimals"]
  4540. ezeros = self.defaults["excellon_exp_zeros"]
  4541. eformat = self.defaults[ "excellon_exp_format"]
  4542. fc_units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4543. if fc_units == 'MM':
  4544. factor = 1 if eunits == 'METRIC' else 0.03937
  4545. else:
  4546. factor = 25.4 if eunits == 'METRIC' else 1
  4547. def make_excellon():
  4548. try:
  4549. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4550. header = 'M48\n'
  4551. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4552. (str(self.version), str(self.version_date))
  4553. header += ';Filename: %s' % str(obj_name) + '\n'
  4554. header += ';Created on : %s' % time_str + '\n'
  4555. if eformat == 'dec':
  4556. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor)
  4557. header += eunits + '\n'
  4558. for tool in obj.tools:
  4559. if eunits == 'METRIC':
  4560. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4561. tool=str(tool),
  4562. dec=2)
  4563. else:
  4564. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4565. tool=str(tool),
  4566. dec=4)
  4567. else:
  4568. if ezeros == 'LZ':
  4569. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  4570. form='ndec', e_zeros='LZ', factor=factor)
  4571. header += '%s,%s\n' % (eunits, 'LZ')
  4572. header += format_exc
  4573. for tool in obj.tools:
  4574. if eunits == 'METRIC':
  4575. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4576. tool=str(tool),
  4577. dec=2)
  4578. else:
  4579. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4580. tool=str(tool),
  4581. dec=4)
  4582. else:
  4583. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  4584. form='ndec', e_zeros='TZ', factor=factor)
  4585. header += '%s,%s\n' % (eunits, 'TZ')
  4586. header += format_exc
  4587. for tool in obj.tools:
  4588. if eunits == 'METRIC':
  4589. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4590. tool=str(tool),
  4591. dec=2)
  4592. else:
  4593. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4594. tool=str(tool),
  4595. dec=4)
  4596. header += '%\n'
  4597. footer = 'M30\n'
  4598. exported_excellon = header
  4599. exported_excellon += excellon_code
  4600. exported_excellon += footer
  4601. with open(filename, 'w') as fp:
  4602. fp.write(exported_excellon)
  4603. self.file_saved.emit("Excellon", filename)
  4604. self.inform.emit("[success] Excellon file exported to " + filename)
  4605. except Exception as e:
  4606. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  4607. return 'fail'
  4608. if use_thread is True:
  4609. with self.proc_container.new("Exporting Excellon") as proc:
  4610. def job_thread_exc(app_obj):
  4611. ret = make_excellon()
  4612. if ret == 'fail':
  4613. self.inform.emit('[ERROR_NOTCL] Could not export Excellon file.')
  4614. return
  4615. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4616. else:
  4617. ret = make_excellon()
  4618. if ret == 'fail':
  4619. self.inform.emit('[ERROR_NOTCL] Could not export Excellon file.')
  4620. return
  4621. def export_dxf(self, obj_name, filename, use_thread=True):
  4622. """
  4623. Exports a Geometry Object to an DXF file.
  4624. :param filename: Path to the DXF file to save to.
  4625. :return:
  4626. """
  4627. self.report_usage("export_dxf()")
  4628. if filename is None:
  4629. filename = self.defaults["global_last_save_folder"]
  4630. self.log.debug("export_dxf()")
  4631. format_exc = ''
  4632. units = ''
  4633. try:
  4634. obj = self.collection.get_by_name(str(obj_name))
  4635. except:
  4636. # TODO: The return behavior has not been established... should raise exception?
  4637. return "Could not retrieve object: %s" % obj_name
  4638. # updated units
  4639. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4640. if units == 'IN' or units == 'INCH':
  4641. units = 'INCH'
  4642. elif units == 'MM' or units == 'METIRC':
  4643. units ='METRIC'
  4644. def make_dxf():
  4645. try:
  4646. dxf_code = obj.export_dxf()
  4647. dxf_code.saveas(filename)
  4648. self.file_saved.emit("DXF", filename)
  4649. self.inform.emit("[success] DXF file exported to " + filename)
  4650. except:
  4651. return 'fail'
  4652. if use_thread is True:
  4653. with self.proc_container.new("Exporting DXF") as proc:
  4654. def job_thread_exc(app_obj):
  4655. ret = make_dxf()
  4656. if ret == 'fail':
  4657. self.inform.emit('[[WARNING_NOTCL]] Could not export DXF file.')
  4658. return
  4659. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4660. else:
  4661. ret = make_dxf()
  4662. if ret == 'fail':
  4663. self.inform.emit('[[WARNING_NOTCL]] Could not export DXF file.')
  4664. return
  4665. def import_svg(self, filename, geo_type='geometry', outname=None):
  4666. """
  4667. Adds a new Geometry Object to the projects and populates
  4668. it with shapes extracted from the SVG file.
  4669. :param filename: Path to the SVG file.
  4670. :param outname:
  4671. :return:
  4672. """
  4673. self.report_usage("import_svg()")
  4674. obj_type = ""
  4675. if geo_type is None or geo_type == "geometry":
  4676. obj_type = "geometry"
  4677. elif geo_type == "gerber":
  4678. obj_type = geo_type
  4679. else:
  4680. self.inform.emit("[ERROR_NOTCL] Not supported type was choosed as parameter. "
  4681. "Only Geometry and Gerber are supported")
  4682. return
  4683. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4684. def obj_init(geo_obj, app_obj):
  4685. geo_obj.import_svg(filename, obj_type, units=units)
  4686. geo_obj.multigeo = False
  4687. with self.proc_container.new("Importing SVG") as proc:
  4688. # Object name
  4689. name = outname or filename.split('/')[-1].split('\\')[-1]
  4690. self.new_object(obj_type, name, obj_init, autoselected=False)
  4691. self.progress.emit(20)
  4692. # Register recent file
  4693. self.file_opened.emit("svg", filename)
  4694. # GUI feedback
  4695. self.inform.emit("[success] Opened: " + filename)
  4696. self.progress.emit(100)
  4697. def import_dxf(self, filename, geo_type='geometry', outname=None):
  4698. """
  4699. Adds a new Geometry Object to the projects and populates
  4700. it with shapes extracted from the DXF file.
  4701. :param filename: Path to the DXF file.
  4702. :param outname:
  4703. :type putname: str
  4704. :return:
  4705. """
  4706. self.report_usage("import_dxf()")
  4707. obj_type = ""
  4708. if geo_type is None or geo_type == "geometry":
  4709. obj_type = "geometry"
  4710. elif geo_type == "gerber":
  4711. obj_type = geo_type
  4712. else:
  4713. self.inform.emit("[ERROR_NOTCL] Not supported type was choosed as parameter. "
  4714. "Only Geometry and Gerber are supported")
  4715. return
  4716. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4717. def obj_init(geo_obj, app_obj):
  4718. geo_obj.import_dxf(filename, obj_type, units=units)
  4719. geo_obj.multigeo = False
  4720. with self.proc_container.new("Importing DXF") as proc:
  4721. # Object name
  4722. name = outname or filename.split('/')[-1].split('\\')[-1]
  4723. self.new_object(obj_type, name, obj_init, autoselected=False)
  4724. self.progress.emit(20)
  4725. # Register recent file
  4726. self.file_opened.emit("dxf", filename)
  4727. # GUI feedback
  4728. self.inform.emit("[success] Opened: " + filename)
  4729. self.progress.emit(100)
  4730. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  4731. """
  4732. Adds a new Geometry Object to the projects and populates
  4733. it with shapes extracted from the SVG file.
  4734. :param filename: Path to the SVG file.
  4735. :param outname:
  4736. :return:
  4737. """
  4738. self.report_usage("import_image()")
  4739. obj_type = ""
  4740. if type is None or type == "geometry":
  4741. obj_type = "geometry"
  4742. elif type == "gerber":
  4743. obj_type = type
  4744. else:
  4745. self.inform.emit("[ERROR_NOTCL] Not supported type was picked as parameter. "
  4746. "Only Geometry and Gerber are supported")
  4747. return
  4748. def obj_init(geo_obj, app_obj):
  4749. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  4750. geo_obj.multigeo = False
  4751. with self.proc_container.new("Importing Image") as proc:
  4752. # Object name
  4753. name = outname or filename.split('/')[-1].split('\\')[-1]
  4754. units = self.general_options_form.general_app_group.units_radio.get_value()
  4755. self.new_object(obj_type, name, obj_init)
  4756. self.progress.emit(20)
  4757. # Register recent file
  4758. self.file_opened.emit("image", filename)
  4759. # GUI feedback
  4760. self.inform.emit("[success] Opened: " + filename)
  4761. self.progress.emit(100)
  4762. def open_gerber(self, filename, follow=False, outname=None):
  4763. """
  4764. Opens a Gerber file, parses it and creates a new object for
  4765. it in the program. Thread-safe.
  4766. :param outname: Name of the resulting object. None causes the
  4767. name to be that of the file.
  4768. :param filename: Gerber file filename
  4769. :type filename: str
  4770. :param follow: If true, the parser will not create polygons, just lines
  4771. following the gerber path.
  4772. :type follow: bool
  4773. :return: None
  4774. """
  4775. # How the object should be initialized
  4776. def obj_init(gerber_obj, app_obj):
  4777. assert isinstance(gerber_obj, FlatCAMGerber), \
  4778. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  4779. # Opening the file happens here
  4780. self.progress.emit(30)
  4781. try:
  4782. gerber_obj.parse_file(filename, follow=follow)
  4783. except IOError:
  4784. app_obj.inform.emit("[ERROR_NOTCL] Failed to open file: " + filename)
  4785. app_obj.progress.emit(0)
  4786. self.inform.emit('[ERROR_NOTCL] Failed to open file: ' + filename)
  4787. return "fail"
  4788. except ParseError as err:
  4789. app_obj.inform.emit("[ERROR_NOTCL] Failed to parse file: " + filename + ". " + str(err))
  4790. app_obj.progress.emit(0)
  4791. self.log.error(str(err))
  4792. return "fail"
  4793. except:
  4794. msg = "[ERROR] An internal error has ocurred. See shell.\n"
  4795. msg += traceback.format_exc()
  4796. app_obj.inform.emit(msg)
  4797. return "fail"
  4798. if gerber_obj.is_empty():
  4799. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  4800. # self.collection.set_active(gerber_obj.options["name"])
  4801. # self.collection.delete_active()
  4802. self.inform.emit("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation.")
  4803. return "fail"
  4804. # Further parsing
  4805. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  4806. if follow is False:
  4807. App.log.debug("open_gerber()")
  4808. else:
  4809. App.log.debug("open_gerber() with 'follow' attribute")
  4810. with self.proc_container.new("Opening Gerber") as proc:
  4811. self.progress.emit(10)
  4812. # Object name
  4813. name = outname or filename.split('/')[-1].split('\\')[-1]
  4814. ### Object creation ###
  4815. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  4816. if ret == 'fail':
  4817. self.inform.emit('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.')
  4818. return
  4819. # Register recent file
  4820. self.file_opened.emit("gerber", filename)
  4821. self.progress.emit(100)
  4822. # GUI feedback
  4823. self.inform.emit("[success] Opened: " + filename)
  4824. def open_excellon(self, filename, outname=None):
  4825. """
  4826. Opens an Excellon file, parses it and creates a new object for
  4827. it in the program. Thread-safe.
  4828. :param outname: Name of the resulting object. None causes the
  4829. name to be that of the file.
  4830. :param filename: Excellon file filename
  4831. :type filename: str
  4832. :return: None
  4833. """
  4834. App.log.debug("open_excellon()")
  4835. #self.progress.emit(10)
  4836. # How the object should be initialized
  4837. def obj_init(excellon_obj, app_obj):
  4838. # self.progress.emit(20)
  4839. try:
  4840. ret = excellon_obj.parse_file(filename)
  4841. if ret == "fail":
  4842. log.debug("Excellon parsing failed.")
  4843. self.inform.emit("[ERROR_NOTCL] This is not Excellon file.")
  4844. return "fail"
  4845. except IOError:
  4846. app_obj.inform.emit("[ERROR_NOTCL] Cannot open file: " + filename)
  4847. log.debug("Could not open Excellon object.")
  4848. self.progress.emit(0) # TODO: self and app_bjj mixed
  4849. return "fail"
  4850. except:
  4851. msg = "[ERROR_NOTCL] An internal error has occurred. See shell.\n"
  4852. msg += traceback.format_exc()
  4853. app_obj.inform.emit(msg)
  4854. return "fail"
  4855. ret = excellon_obj.create_geometry()
  4856. if ret == 'fail':
  4857. log.debug("Could not create geometry for Excellon object.")
  4858. return "fail"
  4859. # if excellon_obj.is_empty():
  4860. # app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  4861. # return "fail"
  4862. for tool in excellon_obj.tools:
  4863. if excellon_obj.tools[tool]['solid_geometry']:
  4864. return
  4865. app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  4866. return "fail"
  4867. with self.proc_container.new("Opening Excellon."):
  4868. # Object name
  4869. name = outname or filename.split('/')[-1].split('\\')[-1]
  4870. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  4871. if ret == 'fail':
  4872. self.inform.emit('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.')
  4873. return
  4874. # Register recent file
  4875. self.file_opened.emit("excellon", filename)
  4876. # GUI feedback
  4877. self.inform.emit("[success] Opened: " + filename)
  4878. # self.progress.emit(100)
  4879. def open_gcode(self, filename, outname=None):
  4880. """
  4881. Opens a G-gcode file, parses it and creates a new object for
  4882. it in the program. Thread-safe.
  4883. :param outname: Name of the resulting object. None causes the
  4884. name to be that of the file.
  4885. :param filename: G-code file filename
  4886. :type filename: str
  4887. :return: None
  4888. """
  4889. App.log.debug("open_gcode()")
  4890. # How the object should be initialized
  4891. def obj_init(job_obj, app_obj_):
  4892. """
  4893. :type app_obj_: App
  4894. """
  4895. assert isinstance(app_obj_, App), \
  4896. "Initializer expected App, got %s" % type(app_obj_)
  4897. self.progress.emit(10)
  4898. try:
  4899. f = open(filename)
  4900. gcode = f.read()
  4901. f.close()
  4902. except IOError:
  4903. app_obj_.inform.emit("[ERROR_NOTCL] Failed to open " + filename)
  4904. self.progress.emit(0)
  4905. return "fail"
  4906. job_obj.gcode = gcode
  4907. self.progress.emit(20)
  4908. ret = job_obj.gcode_parse()
  4909. if ret == "fail":
  4910. self.inform.emit("[ERROR_NOTCL] This is not GCODE")
  4911. return "fail"
  4912. self.progress.emit(60)
  4913. job_obj.create_geometry()
  4914. with self.proc_container.new("Opening G-Code."):
  4915. # Object name
  4916. name = outname or filename.split('/')[-1].split('\\')[-1]
  4917. # New object creation and file processing
  4918. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  4919. if ret == 'fail':
  4920. self.inform.emit("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  4921. "Attempting to create a FlatCAM CNCJob Object from "
  4922. "G-Code file failed during processing")
  4923. return "fail"
  4924. # Register recent file
  4925. self.file_opened.emit("cncjob", filename)
  4926. # GUI feedback
  4927. self.inform.emit("[success] Opened: " + filename)
  4928. self.progress.emit(100)
  4929. def open_project(self, filename, run_from_arg=None):
  4930. """
  4931. Loads a project from the specified file.
  4932. 1) Loads and parses file
  4933. 2) Registers the file as recently opened.
  4934. 3) Calls on_file_new()
  4935. 4) Updates options
  4936. 5) Calls new_object() with the object's from_dict() as init method.
  4937. 6) Calls plot_all()
  4938. :param filename: Name of the file from which to load.
  4939. :type filename: str
  4940. :return: None
  4941. """
  4942. App.log.debug("Opening project: " + filename)
  4943. # Open and parse
  4944. try:
  4945. f = open(filename, 'r')
  4946. except IOError:
  4947. App.log.error("Failed to open project file: %s" % filename)
  4948. self.inform.emit("[ERROR_NOTCL] Failed to open project file: %s" % filename)
  4949. return
  4950. try:
  4951. d = json.load(f, object_hook=dict2obj)
  4952. except:
  4953. App.log.error("Failed to parse project file: %s" % filename)
  4954. self.inform.emit("[ERROR_NOTCL] Failed to parse project file: %s" % filename)
  4955. f.close()
  4956. return
  4957. self.file_opened.emit("project", filename)
  4958. # Clear the current project
  4959. ## NOT THREAD SAFE ##
  4960. if run_from_arg is True:
  4961. pass
  4962. else:
  4963. self.on_file_new()
  4964. #Project options
  4965. self.options.update(d['options'])
  4966. self.project_filename = filename
  4967. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4968. self.set_screen_units(self.options["units"])
  4969. # Re create objects
  4970. App.log.debug("Re-creating objects...")
  4971. for obj in d['objs']:
  4972. def obj_init(obj_inst, app_inst):
  4973. obj_inst.from_dict(obj)
  4974. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  4975. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  4976. self.plot_all()
  4977. self.inform.emit("[success] Project loaded from: " + filename)
  4978. self.should_we_save = False
  4979. App.log.debug("Project loaded")
  4980. def propagate_defaults(self, silent=False):
  4981. """
  4982. This method is used to set default values in classes. It's
  4983. an alternative to project options but allows the use
  4984. of values invisible to the user.
  4985. :return: None
  4986. """
  4987. if silent is False:
  4988. self.log.debug("propagate_defaults()")
  4989. # Which objects to update the given parameters.
  4990. routes = {
  4991. "global_zdownrate": CNCjob,
  4992. "excellon_zeros": Excellon,
  4993. "excellon_format_upper_in": Excellon,
  4994. "excellon_format_lower_in": Excellon,
  4995. "excellon_format_upper_mm": Excellon,
  4996. "excellon_format_lower_mm": Excellon,
  4997. "excellon_units": Excellon,
  4998. "gerber_use_buffer_for_union": Gerber,
  4999. "geometry_multidepth": Geometry
  5000. }
  5001. for param in routes:
  5002. if param in routes[param].defaults:
  5003. try:
  5004. routes[param].defaults[param] = self.defaults[param]
  5005. if silent is False:
  5006. self.log.debug(" " + param + " OK")
  5007. except KeyError:
  5008. if silent is False:
  5009. self.log.debug(" ERROR: " + param + " not in defaults.")
  5010. else:
  5011. # Try extracting the name:
  5012. # classname_param here is param in the object
  5013. if param.find(routes[param].__name__.lower() + "_") == 0:
  5014. p = param[len(routes[param].__name__) + 1:]
  5015. if p in routes[param].defaults:
  5016. routes[param].defaults[p] = self.defaults[param]
  5017. if silent is False:
  5018. self.log.debug(" " + param + " OK!")
  5019. def restore_main_win_geom(self):
  5020. try:
  5021. self.ui.setGeometry(self.defaults["global_def_win_x"],
  5022. self.defaults["global_def_win_y"],
  5023. self.defaults["global_def_win_w"],
  5024. self.defaults["global_def_win_h"])
  5025. self.ui.splitter.setSizes([self.defaults["def_notebook_width"], 0])
  5026. except KeyError:
  5027. pass
  5028. def plot_all(self, zoom=True):
  5029. """
  5030. Re-generates all plots from all objects.
  5031. :return: None
  5032. """
  5033. self.log.debug("Plot_all()")
  5034. for obj in self.collection.get_list():
  5035. def worker_task(obj):
  5036. with self.proc_container.new("Plotting"):
  5037. obj.plot()
  5038. if zoom:
  5039. self.object_plotted.emit(obj)
  5040. # Send to worker
  5041. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  5042. # self.progress.emit(10)
  5043. #
  5044. # def worker_task(app_obj):
  5045. # print "worker task"
  5046. # percentage = 0.1
  5047. # try:
  5048. # delta = 0.9 / len(self.collection.get_list())
  5049. # except ZeroDivisionError:
  5050. # self.progress.emit(0)
  5051. # return
  5052. # for obj in self.collection.get_list():
  5053. # with self.proc_container.new("Plotting"):
  5054. # obj.plot()
  5055. # app_obj.object_plotted.emit(obj)
  5056. #
  5057. # percentage += delta
  5058. # self.progress.emit(int(percentage*100))
  5059. #
  5060. # self.progress.emit(0)
  5061. # self.plots_updated.emit()
  5062. #
  5063. # # Send to worker
  5064. # #self.worker.add_task(worker_task, [self])
  5065. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5066. def register_folder(self, filename):
  5067. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  5068. def register_save_folder(self, filename):
  5069. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  5070. def set_progress_bar(self, percentage, text=""):
  5071. self.ui.progress_bar.setValue(int(percentage))
  5072. def setup_shell(self):
  5073. """
  5074. Creates shell functions. Runs once at startup.
  5075. :return: None
  5076. """
  5077. self.log.debug("setup_shell()")
  5078. def shelp(p=None):
  5079. if not p:
  5080. return "Available commands:\n" + \
  5081. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  5082. "\n\nType help <command_name> for usage.\n Example: help open_gerber"
  5083. if p not in commands:
  5084. return "Unknown command: %s" % p
  5085. return commands[p]["help"]
  5086. # --- Migrated to new architecture ---
  5087. # def options(name):
  5088. # ops = self.collection.get_by_name(str(name)).options
  5089. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  5090. def h(*args):
  5091. """
  5092. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  5093. and standalone parameters into list.
  5094. """
  5095. kwa = {}
  5096. a = []
  5097. n = len(args)
  5098. name = None
  5099. for i in range(n):
  5100. match = re.search(r'^-([a-zA-Z].*)', args[i])
  5101. if match:
  5102. assert name is None
  5103. name = match.group(1)
  5104. continue
  5105. if name is None:
  5106. a.append(args[i])
  5107. else:
  5108. kwa[name] = args[i]
  5109. name = None
  5110. return a, kwa
  5111. @contextmanager
  5112. def wait_signal(signal, timeout=10000):
  5113. """
  5114. Block loop until signal emitted, timeout (ms) elapses
  5115. or unhandled exception happens in a thread.
  5116. :param signal: Signal to wait for.
  5117. """
  5118. loop = QtCore.QEventLoop()
  5119. # Normal termination
  5120. signal.connect(loop.quit)
  5121. # Termination by exception in thread
  5122. self.thread_exception.connect(loop.quit)
  5123. status = {'timed_out': False}
  5124. def report_quit():
  5125. status['timed_out'] = True
  5126. loop.quit()
  5127. yield
  5128. # Temporarily change how exceptions are managed.
  5129. oeh = sys.excepthook
  5130. ex = []
  5131. def except_hook(type_, value, traceback_):
  5132. ex.append(value)
  5133. oeh(type_, value, traceback_)
  5134. sys.excepthook = except_hook
  5135. # Terminate on timeout
  5136. if timeout is not None:
  5137. QtCore.QTimer.singleShot(timeout, report_quit)
  5138. #### Block ####
  5139. loop.exec_()
  5140. # Restore exception management
  5141. sys.excepthook = oeh
  5142. if ex:
  5143. self.raiseTclError(str(ex[0]))
  5144. if status['timed_out']:
  5145. raise Exception('Timed out!')
  5146. def make_docs():
  5147. output = ''
  5148. import collections
  5149. od = collections.OrderedDict(sorted(commands.items()))
  5150. for cmd_, val in od.items():
  5151. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  5152. t = val['help']
  5153. usage_i = t.find('>')
  5154. if usage_i < 0:
  5155. expl = t
  5156. output += expl + '\n\n'
  5157. continue
  5158. expl = t[:usage_i - 1]
  5159. output += expl + '\n\n'
  5160. end_usage_i = t[usage_i:].find('\n')
  5161. if end_usage_i < 0:
  5162. end_usage_i = len(t[usage_i:])
  5163. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  5164. else:
  5165. extras = t[usage_i+end_usage_i+1:]
  5166. parts = [s.strip() for s in extras.split('\n')]
  5167. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  5168. for p in parts:
  5169. output += ' ' + p + '\n\n'
  5170. return output
  5171. '''
  5172. Howto implement TCL shell commands:
  5173. All parameters passed to command should be possible to set as None and test it afterwards.
  5174. This is because we need to see error caused in tcl,
  5175. if None value as default parameter is not allowed TCL will return empty error.
  5176. Use:
  5177. def mycommand(name=None,...):
  5178. Test it like this:
  5179. if name is None:
  5180. self.raise_tcl_error('Argument name is missing.')
  5181. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  5182. otherwise we will miss it and processing will silently continue.
  5183. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  5184. which is catched in exec_command and displayed in TCL shell console with red background.
  5185. Error in console is displayed with TCL trace.
  5186. This behavior works only within main thread,
  5187. errors with promissed tasks can be catched and detected only with log.
  5188. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  5189. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  5190. '''
  5191. commands = {
  5192. 'help': {
  5193. 'fcn': shelp,
  5194. 'help': "Shows list of commands."
  5195. },
  5196. }
  5197. # Import/overwrite tcl commands as objects of TclCommand descendants
  5198. # This modifies the variable 'commands'.
  5199. tclCommands.register_all_commands(self, commands)
  5200. # Add commands to the tcl interpreter
  5201. for cmd in commands:
  5202. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  5203. # Make the tcl puts function return instead of print to stdout
  5204. self.tcl.eval('''
  5205. rename puts original_puts
  5206. proc puts {args} {
  5207. if {[llength $args] == 1} {
  5208. return "[lindex $args 0]"
  5209. } else {
  5210. eval original_puts $args
  5211. }
  5212. }
  5213. ''')
  5214. def setup_recent_items(self):
  5215. # TODO: Move this to constructor
  5216. icons = {
  5217. "gerber": "share/flatcam_icon16.png",
  5218. "excellon": "share/drill16.png",
  5219. "cncjob": "share/cnc16.png",
  5220. "project": "share/project16.png",
  5221. "svg": "share/geometry16.png",
  5222. "dxf": "share/dxf16.png",
  5223. "image": "share/image16.png"
  5224. }
  5225. openers = {
  5226. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  5227. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  5228. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  5229. 'project': self.open_project,
  5230. 'svg': self.import_svg,
  5231. 'dxf': self.import_dxf,
  5232. 'image': self.import_image
  5233. }
  5234. # Open file
  5235. try:
  5236. f = open(self.data_path + '/recent.json')
  5237. except IOError:
  5238. App.log.error("Failed to load recent item list.")
  5239. self.inform.emit("[ERROR_NOTCL] Failed to load recent item list.")
  5240. return
  5241. try:
  5242. self.recent = json.load(f)
  5243. except json.scanner.JSONDecodeError:
  5244. App.log.error("Failed to parse recent item list.")
  5245. self.inform.emit("[ERROR_NOTCL] Failed to parse recent item list.")
  5246. f.close()
  5247. return
  5248. f.close()
  5249. # Closure needed to create callbacks in a loop.
  5250. # Otherwise late binding occurs.
  5251. def make_callback(func, fname):
  5252. def opener():
  5253. func(fname)
  5254. return opener
  5255. def reset_recent():
  5256. # Reset menu
  5257. self.ui.recent.clear()
  5258. self.recent = []
  5259. try:
  5260. f = open(self.data_path + '/recent.json', 'w')
  5261. except IOError:
  5262. App.log.error("Failed to open recent items file for writing.")
  5263. return
  5264. json.dump(self.recent, f)
  5265. # Reset menu
  5266. self.ui.recent.clear()
  5267. # Create menu items
  5268. for recent in self.recent:
  5269. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5270. try:
  5271. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5272. # Attach callback
  5273. o = make_callback(openers[recent["kind"]], recent['filename'])
  5274. action.triggered.connect(o)
  5275. self.ui.recent.addAction(action)
  5276. except KeyError:
  5277. App.log.error("Unsupported file type: %s" % recent["kind"])
  5278. # Last action in Recent Files menu is one that Clear the content
  5279. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  5280. clear_action.triggered.connect(reset_recent)
  5281. self.ui.recent.addSeparator()
  5282. self.ui.recent.addAction(clear_action)
  5283. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  5284. # self.ui.menufilerecent.set_submenu(recent_menu)
  5285. # recent_menu.show_all()
  5286. # self.ui.recent.show()
  5287. self.log.debug("Recent items list has been populated.")
  5288. def setup_component_editor(self):
  5289. # label = QtWidgets.QLabel("Choose an item from Project")
  5290. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  5291. sel_title = QtWidgets.QTextEdit(
  5292. '<b>Shortcut Key List</b>')
  5293. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5294. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5295. # font = self.sel_title.font()
  5296. # font.setPointSize(12)
  5297. # self.sel_title.setFont(font)
  5298. selected_text = '''
  5299. <p><span style="font-size:14px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  5300. <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5301. The normal flow when working in FlatCAM is the following:</span></p>
  5302. <ol>
  5303. <li><span style="font-size:10px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  5304. <br />
  5305. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  5306. &nbsp;</li>
  5307. <li><span style="font-size:10px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  5308. <br />
  5309. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  5310. <br />
  5311. You can change the parameters in this screen and the flow direction is like this:<br />
  5312. <br />
  5313. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  5314. </ol>
  5315. <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  5316. '''
  5317. sel_title.setText(selected_text)
  5318. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5319. self.ui.selected_scroll_area.setWidget(sel_title)
  5320. # tool_title = QtWidgets.QTextEdit(
  5321. # '<b>Shortcut Key List</b>')
  5322. # tool_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5323. # tool_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5324. # # font = self.sel_title.font()
  5325. # # font.setPointSize(12)
  5326. # # self.sel_title.setFont(font)
  5327. #
  5328. # tool_text = '''
  5329. # <p><span style="font-size:14px"><strong>Tool Tab - Choose an Item in Tools Menu</strong></span></p>
  5330. #
  5331. # <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5332. # Some of the functionality of FlatCAM have been implemented as tools (a sort of plugins). </span></p>
  5333. #
  5334. # <p><span style="font-size:10px">Most of the tools are accessible through&nbsp;the Tools menu or by using the associated shortcut keys.<br />
  5335. # Each such a tool, if it needs an object to be used as a source it will provide the way to select this object(s) through a series of comboboxes. The result of using a tool is either a Geometry, an information that can be used in the app or it can be a file that can be saved.</span></p>
  5336. #
  5337. # <ol>
  5338. # </ol>
  5339. #
  5340. # <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: &#39;`&#39; (key left to 1).</span></p>
  5341. #
  5342. # '''
  5343. #
  5344. # tool_title.setText(tool_text)
  5345. # tool_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5346. #
  5347. # self.ui.tool_scroll_area.setWidget(tool_title)
  5348. def setup_obj_classes(self):
  5349. """
  5350. Sets up application specifics on the FlatCAMObj class.
  5351. :return: None
  5352. """
  5353. FlatCAMObj.app = self
  5354. ObjectCollection.app = self
  5355. FCProcess.app = self
  5356. FCProcessContainer.app = self
  5357. def version_check(self):
  5358. """
  5359. Checks for the latest version of the program. Alerts the
  5360. user if theirs is outdated. This method is meant to be run
  5361. in a separate thread.
  5362. :return: None
  5363. """
  5364. self.log.debug("version_check()")
  5365. if self.general_defaults_form.general_gui_group.send_stats_cb.get_value() is True:
  5366. full_url = App.version_url + \
  5367. "?s=" + str(self.defaults['global_serial']) + \
  5368. "&v=" + str(self.version) + \
  5369. "&os=" + str(self.os) + \
  5370. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  5371. else:
  5372. # no_stats dict; just so it won't break things on website
  5373. no_ststs_dict = {}
  5374. no_ststs_dict["global_ststs"] = {}
  5375. full_url = App.version_url + \
  5376. "?s=" + str(self.defaults['global_serial']) + \
  5377. "&v=" + str(self.version) + \
  5378. "&os=" + str(self.os) + \
  5379. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  5380. App.log.debug("Checking for updates @ %s" % full_url)
  5381. ### Get the data
  5382. try:
  5383. f = urllib.request.urlopen(full_url)
  5384. except:
  5385. # App.log.warning("Failed checking for latest version. Could not connect.")
  5386. self.log.warning("Failed checking for latest version. Could not connect.")
  5387. self.inform.emit("[WARNING_NOTCL] Failed checking for latest version. Could not connect.")
  5388. return
  5389. try:
  5390. data = json.load(f)
  5391. except Exception as e:
  5392. App.log.error("Could not parse information about latest version.")
  5393. self.inform.emit("[ERROR_NOTCL] Could not parse information about latest version.")
  5394. App.log.debug("json.load(): %s" % str(e))
  5395. f.close()
  5396. return
  5397. f.close()
  5398. ### Latest version?
  5399. if self.version >= data["version"]:
  5400. App.log.debug("FlatCAM is up to date!")
  5401. self.inform.emit("[success] FlatCAM is up to date!")
  5402. return
  5403. App.log.debug("Newer version available.")
  5404. self.message.emit(
  5405. "Newer Version Available",
  5406. str("There is a newer version of FlatCAM " +
  5407. "available for download:<br><br>" +
  5408. "<B>" + data["name"] + "</b><br>" +
  5409. data["message"].replace("\n", "<br>")),
  5410. "info"
  5411. )
  5412. def on_zoom_fit(self, event):
  5413. """
  5414. Callback for zoom-out request. This can be either from the corresponding
  5415. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  5416. with axes limits from the geometry bounds of all objects.
  5417. :param event: Ignored.
  5418. :return: None
  5419. """
  5420. self.plotcanvas.fit_view()
  5421. def disable_all_plots(self):
  5422. self.report_usage("disable_all_plots()")
  5423. self.disable_plots(self.collection.get_list())
  5424. self.inform.emit("[success]All plots disabled.")
  5425. def disable_other_plots(self):
  5426. self.report_usage("disable_other_plots()")
  5427. self.disable_plots(self.collection.get_non_selected())
  5428. self.inform.emit("[success]All non selected plots disabled.")
  5429. def enable_all_plots(self):
  5430. self.report_usage("enable_all_plots()")
  5431. self.enable_plots(self.collection.get_list())
  5432. self.inform.emit("[success]All plots enabled.")
  5433. # TODO: FIX THIS
  5434. '''
  5435. By default this is not threaded
  5436. If threaded the app give warnings like this:
  5437. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5438. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5439. '''
  5440. def enable_plots(self, objects, threaded=False):
  5441. if threaded is True:
  5442. def worker_task(app_obj):
  5443. percentage = 0.1
  5444. try:
  5445. delta = 0.9 / len(objects)
  5446. except ZeroDivisionError:
  5447. self.progress.emit(0)
  5448. return
  5449. for obj in objects:
  5450. obj.options['plot'] = True
  5451. percentage += delta
  5452. self.progress.emit(int(percentage*100))
  5453. self.progress.emit(0)
  5454. self.plots_updated.emit()
  5455. self.collection.update_view()
  5456. # Send to worker
  5457. # self.worker.add_task(worker_task, [self])
  5458. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5459. else:
  5460. for obj in objects:
  5461. obj.options['plot'] = True
  5462. self.progress.emit(0)
  5463. self.plots_updated.emit()
  5464. self.collection.update_view()
  5465. # TODO: FIX THIS
  5466. '''
  5467. By default this is not threaded
  5468. If threaded the app give warnings like this:
  5469. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5470. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5471. '''
  5472. def disable_plots(self, objects, threaded=False):
  5473. # TODO: This method is very similar to replot_all. Try to merge.
  5474. """
  5475. Disables plots
  5476. :param objects: list
  5477. Objects to be disabled
  5478. :return:
  5479. """
  5480. if threaded is True:
  5481. self.progress.emit(10)
  5482. def worker_task(app_obj):
  5483. percentage = 0.1
  5484. try:
  5485. delta = 0.9 / len(objects)
  5486. except ZeroDivisionError:
  5487. self.progress.emit(0)
  5488. return
  5489. for obj in objects:
  5490. obj.options['plot'] = False
  5491. percentage += delta
  5492. self.progress.emit(int(percentage*100))
  5493. self.progress.emit(0)
  5494. self.plots_updated.emit()
  5495. self.collection.update_view()
  5496. # Send to worker
  5497. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5498. else:
  5499. for obj in objects:
  5500. obj.options['plot'] = False
  5501. self.plots_updated.emit()
  5502. self.collection.update_view()
  5503. def clear_plots(self):
  5504. objects = self.collection.get_list()
  5505. for obj in objects:
  5506. obj.clear(obj == objects[-1])
  5507. # Clear pool to free memory
  5508. self.clear_pool()
  5509. def generate_cnc_job(self, objects):
  5510. self.report_usage("generate_cnc_job()")
  5511. # for obj in objects:
  5512. # obj.generatecncjob()
  5513. for obj in objects:
  5514. obj.on_generatecnc_button_click()
  5515. def save_project(self, filename):
  5516. """
  5517. Saves the current project to the specified file.
  5518. :param filename: Name of the file in which to save.
  5519. :type filename: str
  5520. :return: None
  5521. """
  5522. self.log.debug("save_project()")
  5523. with self.proc_container.new("Saving FlatCAM Project") as proc:
  5524. ## Capture the latest changes
  5525. # Current object
  5526. try:
  5527. self.collection.get_active().read_form()
  5528. except:
  5529. self.log.debug("[WARNING] There was no active object")
  5530. pass
  5531. # Project options
  5532. self.options_read_form()
  5533. # Serialize the whole project
  5534. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  5535. "options": self.options,
  5536. "version": self.version}
  5537. # Open file
  5538. try:
  5539. f = open(filename, 'w')
  5540. except IOError:
  5541. App.log.error("[ERROR] Failed to open file for saving: %s", filename)
  5542. return
  5543. # Write
  5544. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  5545. f.close()
  5546. # verification of the saved project
  5547. # Open and parse
  5548. try:
  5549. saved_f = open(filename, 'r')
  5550. except IOError:
  5551. self.inform.emit("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it." % filename)
  5552. return
  5553. try:
  5554. saved_d = json.load(saved_f, object_hook=dict2obj)
  5555. except:
  5556. self.inform.emit("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it." % filename)
  5557. f.close()
  5558. return
  5559. saved_f.close()
  5560. if 'version' in saved_d:
  5561. self.inform.emit("[success] Project saved to: %s" % filename)
  5562. else:
  5563. self.inform.emit("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it." % filename)
  5564. def on_options_app2project(self):
  5565. """
  5566. Callback for Options->Transfer Options->App=>Project. Copies options
  5567. from application defaults to project defaults.
  5568. :return: None
  5569. """
  5570. self.report_usage("on_options_app2project")
  5571. self.defaults_read_form()
  5572. self.options.update(self.defaults)
  5573. self.options_write_form()
  5574. def on_options_project2app(self):
  5575. """
  5576. Callback for Options->Transfer Options->Project=>App. Copies options
  5577. from project defaults to application defaults.
  5578. :return: None
  5579. """
  5580. self.report_usage("on_options_project2app")
  5581. self.options_read_form()
  5582. self.defaults.update(self.options)
  5583. self.defaults_write_form()
  5584. def on_options_project2object(self):
  5585. """
  5586. Callback for Options->Transfer Options->Project=>Object. Copies options
  5587. from project defaults to the currently selected object.
  5588. :return: None
  5589. """
  5590. self.report_usage("on_options_project2object")
  5591. self.options_read_form()
  5592. obj = self.collection.get_active()
  5593. if obj is None:
  5594. self.inform.emit("WARNING: No object selected.")
  5595. return
  5596. for option in self.options:
  5597. if option.find(obj.kind + "_") == 0:
  5598. oname = option[len(obj.kind) + 1:]
  5599. obj.options[oname] = self.options[option]
  5600. obj.to_form() # Update UI
  5601. def on_options_object2project(self):
  5602. """
  5603. Callback for Options->Transfer Options->Object=>Project. Copies options
  5604. from the currently selected object to project defaults.
  5605. :return: None
  5606. """
  5607. self.report_usage("on_options_object2project")
  5608. obj = self.collection.get_active()
  5609. if obj is None:
  5610. self.inform.emit("WARNING: No object selected.")
  5611. return
  5612. obj.read_form()
  5613. for option in obj.options:
  5614. if option in ['name']: # TODO: Handle this better...
  5615. continue
  5616. self.options[obj.kind + "_" + option] = obj.options[option]
  5617. self.options_write_form()
  5618. def on_options_object2app(self):
  5619. """
  5620. Callback for Options->Transfer Options->Object=>App. Copies options
  5621. from the currently selected object to application defaults.
  5622. :return: None
  5623. """
  5624. self.report_usage("on_options_object2app")
  5625. obj = self.collection.get_active()
  5626. if obj is None:
  5627. self.inform.emit("WARNING: No object selected.")
  5628. return
  5629. obj.read_form()
  5630. for option in obj.options:
  5631. if option in ['name']: # TODO: Handle this better...
  5632. continue
  5633. self.defaults[obj.kind + "_" + option] = obj.options[option]
  5634. self.defaults_write_form()
  5635. def on_options_app2object(self):
  5636. """
  5637. Callback for Options->Transfer Options->App=>Object. Copies options
  5638. from application defaults to the currently selected object.
  5639. :return: None
  5640. """
  5641. self.report_usage("on_options_app2object")
  5642. self.defaults_read_form()
  5643. obj = self.collection.get_active()
  5644. if obj is None:
  5645. self.inform.emit("WARNING: No object selected.")
  5646. return
  5647. for option in self.defaults:
  5648. if option.find(obj.kind + "_") == 0:
  5649. oname = option[len(obj.kind) + 1:]
  5650. obj.options[oname] = self.defaults[option]
  5651. obj.to_form() # Update UI
  5652. # end of file