FlatCAMApp.py 485 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844
  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 urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import ctypes
  20. import tkinter as tk
  21. from PyQt5 import QtPrintSupport
  22. from contextlib import contextmanager
  23. import gc
  24. from xml.dom.minidom import parseString as parse_xml_string
  25. from multiprocessing.connection import Listener, Client
  26. from multiprocessing import Pool
  27. import socket
  28. from array import array
  29. # #######################################
  30. # # Imports part of FlatCAM ##
  31. # #######################################
  32. from ObjectCollection import *
  33. from FlatCAMObj import *
  34. from flatcamGUI.PlotCanvas import *
  35. from flatcamGUI.FlatCAMGUI import *
  36. from FlatCAMCommon import LoudDict
  37. from FlatCAMPostProc import load_postprocessors
  38. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  39. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  40. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  41. from FlatCAMProcess import *
  42. from FlatCAMWorkerStack import WorkerStack
  43. from flatcamGUI.VisPyVisuals import Color
  44. from vispy.gloo.util import _screenshot
  45. from vispy.io import write_png
  46. from flatcamTools import *
  47. import tclCommands
  48. import gettext
  49. import FlatCAMTranslation as fcTranslate
  50. import builtins
  51. if sys.platform == 'win32':
  52. import winreg
  53. fcTranslate.apply_language('strings')
  54. if '_' not in builtins.__dict__:
  55. _ = gettext.gettext
  56. # ########################################
  57. # # App ###
  58. # ########################################
  59. class App(QtCore.QObject):
  60. """
  61. The main application class. The constructor starts the GUI.
  62. """
  63. # Get Cmd Line Options
  64. cmd_line_shellfile = ''
  65. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  66. try:
  67. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  68. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  69. except getopt.GetoptError:
  70. print(cmd_line_help)
  71. sys.exit(2)
  72. for opt, arg in cmd_line_options:
  73. if opt == '-h':
  74. print(cmd_line_help)
  75. sys.exit()
  76. elif opt == '--shellfile':
  77. cmd_line_shellfile = arg
  78. # ## Logging ###
  79. log = logging.getLogger('base')
  80. log.setLevel(logging.DEBUG)
  81. # log.setLevel(logging.WARNING)
  82. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  83. handler = logging.StreamHandler()
  84. handler.setFormatter(formatter)
  85. log.addHandler(handler)
  86. # ##########################################################################
  87. # ################## Version and VERSION DATE ##############################
  88. # ##########################################################################
  89. version = 8.97
  90. version_date = "2019/09/15"
  91. beta = True
  92. # current date now
  93. date = str(datetime.today()).rpartition('.')[0]
  94. date = ''.join(c for c in date if c not in ':-')
  95. date = date.replace(' ', '_')
  96. # URL for update checks and statistics
  97. version_url = "http://flatcam.org/version"
  98. # App URL
  99. app_url = "http://flatcam.org"
  100. # Manual URL
  101. manual_url = "http://flatcam.org/manual/index.html"
  102. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  103. gerber_spec_url ="https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  104. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  105. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  106. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  107. # this variable will hold the project status
  108. # if True it will mean that the project was modified and not saved
  109. should_we_save = False
  110. # flag is True if saving action has been triggered
  111. save_in_progress = False
  112. # ###########################################################################
  113. # ############################# Signals ################################
  114. # ###########################################################################
  115. # Inform the user
  116. # Handled by:
  117. # * App.info() --> Print on the status bar
  118. inform = QtCore.pyqtSignal(str)
  119. app_quit = QtCore.pyqtSignal()
  120. # General purpose background task
  121. worker_task = QtCore.pyqtSignal(dict)
  122. # File opened
  123. # Handled by:
  124. # * register_folder()
  125. # * register_recent()
  126. # Note: Setting the parameters to unicode does not seem
  127. # to have an effect. Then are received as Qstring
  128. # anyway.
  129. # File type and filename
  130. file_opened = QtCore.pyqtSignal(str, str)
  131. # File type and filename
  132. file_saved = QtCore.pyqtSignal(str, str)
  133. # Percentage of progress
  134. progress = QtCore.pyqtSignal(int)
  135. plots_updated = QtCore.pyqtSignal()
  136. # Emitted by new_object() and passes the new object as argument, plot flag.
  137. # on_object_created() adds the object to the collection, plots on appropriate flag
  138. # and emits new_object_available.
  139. object_created = QtCore.pyqtSignal(object, bool, bool)
  140. # Emitted when a object has been changed (like scaled, mirrored)
  141. object_changed = QtCore.pyqtSignal(object)
  142. # Emitted after object has been plotted.
  143. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  144. object_plotted = QtCore.pyqtSignal(object)
  145. # Emitted when a new object has been added or deleted from/to the collection
  146. object_status_changed = QtCore.pyqtSignal(object, str)
  147. message = QtCore.pyqtSignal(str, str, str)
  148. # Emmited when shell command is finished(one command only)
  149. shell_command_finished = QtCore.pyqtSignal(object)
  150. # Emitted when multiprocess pool has been recreated
  151. pool_recreated = QtCore.pyqtSignal(object)
  152. # Emitted when an unhandled exception happens
  153. # in the worker task.
  154. thread_exception = QtCore.pyqtSignal(object)
  155. # used to signal that there are arguments for the app
  156. args_at_startup = QtCore.pyqtSignal(list)
  157. # a reusable signal to replot a list of objects
  158. # should be disconnected after use so it can be reused
  159. replot_signal = pyqtSignal(list)
  160. def __init__(self, user_defaults=True, post_gui=None):
  161. """
  162. Starts the application.
  163. :return: app
  164. :rtype: App
  165. """
  166. App.log.info("FlatCAM Starting...")
  167. self.main_thread = QtWidgets.QApplication.instance().thread()
  168. # ############################################################################
  169. # # ################# OS-specific ############################################
  170. # ############################################################################
  171. portable = False
  172. # Folder for user settings.
  173. if sys.platform == 'win32':
  174. # #########################################################################
  175. # Setup the listening thread for another instance launching with args #####
  176. # #########################################################################
  177. # make sure the thread is stored by using a self. otherwise it's garbage collected
  178. self.th = QtCore.QThread()
  179. self.th.start(priority=QtCore.QThread.LowestPriority)
  180. self.new_launch = ArgsThread()
  181. self.new_launch.open_signal[list].connect(self.on_startup_args)
  182. self.new_launch.moveToThread(self.th)
  183. self.new_launch.start.emit()
  184. from win32com.shell import shell, shellcon
  185. if platform.architecture()[0] == '32bit':
  186. App.log.debug("Win32!")
  187. else:
  188. App.log.debug("Win64!")
  189. # #########################################################################
  190. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  191. # #########################################################################
  192. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  193. try:
  194. with open(config_file, 'r') as f:
  195. try:
  196. for line in f:
  197. param = str(line).rpartition('=')
  198. if param[0] == 'portable':
  199. try:
  200. portable = eval(param[2])
  201. except NameError:
  202. portable = False
  203. except Exception as e:
  204. log.debug('App.__init__() -->%s' % str(e))
  205. return
  206. except FileNotFoundError:
  207. pass
  208. if portable is False:
  209. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  210. else:
  211. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  212. self.os = 'windows'
  213. else: # Linux/Unix/MacOS
  214. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  215. self.os = 'unix'
  216. # ##########################################################################
  217. # ################## Setup folders and files ###############################
  218. # ##########################################################################
  219. if not os.path.exists(self.data_path):
  220. os.makedirs(self.data_path)
  221. App.log.debug('Created data folder: ' + self.data_path)
  222. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  223. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  224. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  225. if not os.path.exists(self.postprocessorpaths):
  226. os.makedirs(self.postprocessorpaths)
  227. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  228. # create current_defaults.FlatConfig file if there is none
  229. try:
  230. f = open(self.data_path + '/current_defaults.FlatConfig')
  231. f.close()
  232. except IOError:
  233. App.log.debug('Creating empty current_defaults.FlatConfig')
  234. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  235. json.dump({}, f)
  236. f.close()
  237. # create factory_defaults.FlatConfig file if there is none
  238. try:
  239. f = open(self.data_path + '/factory_defaults.FlatConfig')
  240. f.close()
  241. except IOError:
  242. App.log.debug('Creating empty factory_defaults.FlatConfig')
  243. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  244. json.dump({}, f)
  245. f.close()
  246. try:
  247. f = open(self.data_path + '/recent.json')
  248. f.close()
  249. except IOError:
  250. App.log.debug('Creating empty recent.json')
  251. f = open(self.data_path + '/recent.json', 'w')
  252. json.dump([], f)
  253. f.close()
  254. try:
  255. fp = open(self.data_path + '/recent_projects.json')
  256. fp.close()
  257. except IOError:
  258. App.log.debug('Creating empty recent_projects.json')
  259. fp = open(self.data_path + '/recent_projects.json', 'w')
  260. json.dump([], fp)
  261. fp.close()
  262. # Application directory. CHDIR to it. Otherwise, trying to load
  263. # GUI icons will fail as their path is relative.
  264. # This will fail under cx_freeze ...
  265. self.app_home = os.path.dirname(os.path.realpath(__file__))
  266. App.log.debug("Application path is " + self.app_home)
  267. App.log.debug("Started in " + os.getcwd())
  268. # cx_freeze workaround
  269. if os.path.isfile(self.app_home):
  270. self.app_home = os.path.dirname(self.app_home)
  271. os.chdir(self.app_home)
  272. # #############################################################################
  273. # ##################### CREATE MULTIPROCESSING POOL ###########################
  274. # #############################################################################
  275. self.pool = Pool()
  276. # ##########################################################################
  277. # ################## Setting the Splash Screen #############################
  278. # ##########################################################################
  279. settings = QSettings("Open Source", "FlatCAM")
  280. if settings.contains("splash_screen"):
  281. show_splash = settings.value("splash_screen")
  282. else:
  283. settings.setValue('splash_screen', 1)
  284. # This will write the setting to the platform specific storage.
  285. del settings
  286. show_splash = 1
  287. if show_splash:
  288. splash_pix = QtGui.QPixmap('share/splash.png')
  289. splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  290. # splash.setMask(splash_pix.mask())
  291. # move splashscreen to the current monitor
  292. desktop = QtWidgets.QApplication.desktop()
  293. screen = desktop.screenNumber(QtGui.QCursor.pos())
  294. current_screen_center = desktop.availableGeometry(screen).center()
  295. splash.move(current_screen_center - splash.rect().center())
  296. splash.show()
  297. splash.showMessage(_("FlatCAM is initializing ..."),
  298. alignment=Qt.AlignBottom | Qt.AlignLeft,
  299. color=QtGui.QColor("gray"))
  300. # #############################################################################
  301. # ##################### Initialize GUI ########################################
  302. # #############################################################################
  303. # FlatCAM colors used in plotting
  304. self.FC_light_green = '#BBF268BF'
  305. self.FC_dark_green = '#006E20BF'
  306. self.FC_light_blue = '#a5a5ffbf'
  307. self.FC_dark_blue = '#0000ffbf'
  308. QtCore.QObject.__init__(self)
  309. self.ui = FlatCAMGUI(self.version, self.beta, self)
  310. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  311. self.ui.final_save.connect(self.final_save)
  312. # #############################################################################
  313. # ############################## Data #########################################
  314. # #############################################################################
  315. self.recent = []
  316. self.recent_projects = []
  317. self.clipboard = QtWidgets.QApplication.clipboard()
  318. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  319. self.project_filename = None
  320. self.toggle_units_ignore = False
  321. # self.defaults_form = PreferencesUI()
  322. # when adding entries here read the comments in the method found bellow named:
  323. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  324. self.defaults_form_fields = {
  325. # General App
  326. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  327. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  328. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  329. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  330. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  331. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  332. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  333. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  334. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  335. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  336. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  337. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  338. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  339. # General GUI Preferences
  340. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  341. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  342. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  343. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  344. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  345. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  346. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  347. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  348. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  349. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  350. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  351. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  352. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  353. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  354. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  355. # General GUI Settings
  356. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  357. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  358. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  359. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  360. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  361. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  362. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  363. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  364. # Gerber General
  365. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  366. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  367. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  368. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  369. # Gerber Options
  370. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  371. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  372. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  373. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  374. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  375. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  376. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  377. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  378. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  379. # Gerber Advanced Options
  380. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  381. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  382. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  383. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  384. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  385. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  386. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  387. # Gerber Export
  388. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  389. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  390. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  391. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  392. # Gerber Editor
  393. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  394. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  395. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  396. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  397. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  398. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  399. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  400. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  401. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  402. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  403. "gerber_editor_circ_angle":
  404. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  405. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  406. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  407. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  408. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  409. # Excellon General
  410. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  411. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  412. "excellon_format_upper_in":
  413. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  414. "excellon_format_lower_in":
  415. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  416. "excellon_format_upper_mm":
  417. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  418. "excellon_format_lower_mm":
  419. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  420. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  421. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  422. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  423. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  424. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  425. # Excellon Options
  426. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  427. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  428. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  429. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  430. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  431. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  432. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  433. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  434. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  435. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  436. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  437. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  438. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  439. # Excellon Advanced Options
  440. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  441. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  442. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  443. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  444. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  445. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  446. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  447. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  448. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  449. # Excellon Export
  450. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  451. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  452. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  453. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  454. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  455. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  456. # Excellon Editor
  457. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  458. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  459. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  460. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  461. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  462. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  463. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  464. "excellon_editor_circ_angle":
  465. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  466. # Excellon Slots
  467. "excellon_editor_slot_direction":
  468. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  469. "excellon_editor_slot_angle":
  470. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  471. "excellon_editor_slot_length":
  472. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  473. # Excellon Slots
  474. "excellon_editor_slot_array_size":
  475. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  476. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  477. "excellon_editor_slot_lin_pitch":
  478. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  479. "excellon_editor_slot_lin_angle":
  480. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  481. "excellon_editor_slot_circ_dir":
  482. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  483. "excellon_editor_slot_circ_angle":
  484. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  485. # Geometry General
  486. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  487. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  488. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  489. # Geometry Options
  490. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  491. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  492. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  493. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  494. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  495. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  496. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  497. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  498. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  499. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  500. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  501. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  502. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  503. # Geometry Advanced Options
  504. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  505. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  506. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  507. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  508. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  509. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  510. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  511. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  512. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  513. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  514. # Geometry Editor
  515. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  516. # CNCJob General
  517. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  518. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  519. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  520. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  521. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  522. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  523. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  524. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  525. # CNC Job Options
  526. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  527. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  528. # CNC Job Advanced Options
  529. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  530. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  531. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  532. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  533. # NCC Tool
  534. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  535. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  536. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  537. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  538. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  539. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  540. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  541. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  542. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  543. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  544. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  545. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  546. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  547. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  548. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  549. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  550. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  551. # CutOut Tool
  552. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  553. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  554. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  555. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  556. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  557. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  558. # Paint Area Tool
  559. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  560. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  561. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  562. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  563. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  564. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  565. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  566. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  567. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  568. # 2-sided Tool
  569. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  570. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  571. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  572. # Film Tool
  573. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  574. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  575. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  576. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  577. # Panelize Tool
  578. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  579. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  580. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  581. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  582. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  583. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  584. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  585. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  586. # Calculators Tool
  587. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  588. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  589. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  590. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  591. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  592. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  593. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  594. # Transformations Tool
  595. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  596. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  597. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  598. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  599. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  600. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  601. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  602. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  603. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  604. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  605. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  606. # SolderPaste Dispensing Tool
  607. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  608. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  609. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  610. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  611. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  612. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  613. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  614. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  615. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  616. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  617. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  618. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  619. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  620. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  621. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  622. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  623. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  624. # file associations
  625. "fa_excellon": self.ui.fa_defaults_form.fa_excellon_group.exc_list_text,
  626. "fa_gcode": self.ui.fa_defaults_form.fa_gcode_group.gco_list_text,
  627. # "fa_geometry": self.ui.fa_defaults_form.fa_geometry_group.close_paths_cb,
  628. "fa_gerber": self.ui.fa_defaults_form.fa_gerber_group.grb_list_text,
  629. }
  630. # ############################
  631. # ### LOAD POSTPROCESSORS ####
  632. # ############################
  633. self.postprocessors = load_postprocessors(self)
  634. for name in list(self.postprocessors.keys()):
  635. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  636. if name.partition('_')[0] == 'Paste':
  637. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  638. continue
  639. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  640. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  641. if name == 'hpgl':
  642. continue
  643. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  644. # ############################
  645. # ### LOAD LANGUAGES ####
  646. # ############################
  647. self.languages = fcTranslate.load_languages()
  648. for name in sorted(self.languages.values()):
  649. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  650. self.defaults = LoudDict()
  651. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  652. self.defaults.update({
  653. # Global APP Preferences
  654. "first_run": True,
  655. "units": "IN",
  656. "global_serial": 0,
  657. "global_stats": {},
  658. "global_tabs_detachable": True,
  659. "global_app_level": 'b',
  660. "global_portable": False,
  661. "global_language": 'English',
  662. "global_version_check": True,
  663. "global_send_stats": True,
  664. "global_pan_button": '2',
  665. "global_mselect_key": 'Control',
  666. "global_project_at_startup": False,
  667. "global_project_autohide": True,
  668. "global_toggle_tooltips": True,
  669. "global_worker_number": 2,
  670. "global_tolerance": 0.01,
  671. "global_open_style": True,
  672. "global_delete_confirmation": True,
  673. "global_compression_level": 3,
  674. "global_save_compressed": True,
  675. # Global GUI Preferences
  676. "global_gridx": 0.0393701,
  677. "global_gridy": 0.0393701,
  678. "global_snap_max": 0.001968504,
  679. "global_workspace": False,
  680. "global_workspaceT": "A4P",
  681. "global_grid_context_menu": {
  682. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  683. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  684. },
  685. "global_plot_fill": '#BBF268BF',
  686. "global_plot_line": '#006E20BF',
  687. "global_sel_fill": '#a5a5ffbf',
  688. "global_sel_line": '#0000ffbf',
  689. "global_alt_sel_fill": '#BBF268BF',
  690. "global_alt_sel_line": '#006E20BF',
  691. "global_draw_color": '#FF0000',
  692. "global_sel_draw_color": '#0000FF',
  693. "global_proj_item_color": '#000000',
  694. "global_proj_item_dis_color": '#b7b7cb',
  695. "global_toolbar_view": 511,
  696. "global_background_timeout": 300000, # Default value is 5 minutes
  697. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  698. # (python trace only for unknown errors),
  699. # 1 = show trace(show trace always),
  700. # 2 = (For the future).
  701. # Persistence
  702. "global_last_folder": None,
  703. "global_last_save_folder": None,
  704. # Default window geometry
  705. "global_def_win_x": 100,
  706. "global_def_win_y": 100,
  707. "global_def_win_w": 1024,
  708. "global_def_win_h": 650,
  709. "global_def_notebook_width": 1,
  710. # Constants...
  711. "global_defaults_save_period_ms": 20000, # Time between default saves.
  712. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  713. "global_shell_at_startup": False, # Show the shell at startup.
  714. "global_recent_limit": 10, # Max. items in recent list.
  715. "fit_key": 'V',
  716. "zoom_out_key": '-',
  717. "zoom_in_key": '=',
  718. "grid_toggle_key": 'G',
  719. "global_zoom_ratio": 1.5,
  720. "global_point_clipboard_format": "(%.4f, %.4f)",
  721. "global_zdownrate": None,
  722. # autocomplete keywords
  723. "global_autocomplete_keywords":
  724. ['all', 'angle_x', 'angle_y', 'axis', 'axisoffset', 'box', 'center_x', 'center_y',
  725. 'columns', 'combine', 'connect', 'contour', 'depthperpass', 'dia', 'diatol', 'dist',
  726. 'drilled_dias', 'drillz', 'pp',
  727. 'gridoffsety', 'gridx', 'gridy', 'has_offset', 'holes', 'margin', 'method',
  728. 'milled_dias',
  729. 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order', 'outname',
  730. 'overlap', 'passes', 'postamble', 'ppname_e', 'ppname_g', 'preamble', 'radius', 'ref',
  731. 'rest', 'rows', 'scale_factor', 'spacing_columns', 'spacing_rows', 'spindlespeed',
  732. 'use_threads', 'value', 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move',
  733. 'default', 'feedrate_z', 'grbl_11', 'grbl_laser', 'hpgl', 'line_xyz', 'marlin',
  734. 'Paste_1', 'Repetier', 'Toolchange_Custom', 'Roland_MDX_20', 'Toolchange_manual',
  735. 'Toolchange_Probe_MACH3', 'dwell', 'dwelltime', 'toolchange_xy', 'iso_type',
  736. 'Desktop', 'FlatPrj', 'FlatConfig', 'Users', 'Documents', 'My Documents', 'Marius'
  737. ],
  738. # General GUI Settings
  739. "global_hover": False,
  740. "global_selection_shape": True,
  741. "global_layout": "compact",
  742. # Gerber General
  743. "gerber_plot": True,
  744. "gerber_solid": True,
  745. "gerber_multicolored": False,
  746. "gerber_circle_steps": 128,
  747. "gerber_use_buffer_for_union": True,
  748. # Gerber Options
  749. "gerber_isotooldia": 0.00787402,
  750. "gerber_isopasses": 1,
  751. "gerber_isooverlap": 0.00393701,
  752. "gerber_milling_type": "cl",
  753. "gerber_combine_passes": False,
  754. "gerber_noncoppermargin": 0.00393701,
  755. "gerber_noncopperrounded": False,
  756. "gerber_bboxmargin": 0.00393701,
  757. "gerber_bboxrounded": False,
  758. # Gerber Advanced Options
  759. "gerber_aperture_display": False,
  760. "gerber_aperture_scale_factor": 1.0,
  761. "gerber_aperture_buffer_factor": 0.0,
  762. "gerber_follow": False,
  763. "gerber_buffering": "full",
  764. "gerber_simplification": False,
  765. "gerber_simp_tolerance": 0.0005,
  766. # Gerber Export
  767. "gerber_exp_units": 'IN',
  768. "gerber_exp_integer": 2,
  769. "gerber_exp_decimals": 4,
  770. "gerber_exp_zeros": 'L',
  771. # Gerber Editor
  772. "gerber_editor_sel_limit": 30,
  773. "gerber_editor_newcode": 10,
  774. "gerber_editor_newsize": 0.8,
  775. "gerber_editor_newtype": 'C',
  776. "gerber_editor_newdim": "0.5, 0.5",
  777. "gerber_editor_array_size": 5,
  778. "gerber_editor_lin_axis": 'X',
  779. "gerber_editor_lin_pitch": 1,
  780. "gerber_editor_lin_angle": 0.0,
  781. "gerber_editor_circ_dir": 'CW',
  782. "gerber_editor_circ_angle": 0.0,
  783. "gerber_editor_scale_f": 1.0,
  784. "gerber_editor_buff_f": 0.1,
  785. "gerber_editor_ma_low": 0.0,
  786. "gerber_editor_ma_high": 1.0,
  787. # Excellon General
  788. "excellon_plot": True,
  789. "excellon_solid": True,
  790. "excellon_format_upper_in": 2,
  791. "excellon_format_lower_in": 4,
  792. "excellon_format_upper_mm": 3,
  793. "excellon_format_lower_mm": 3,
  794. "excellon_zeros": "L",
  795. "excellon_units": "INCH",
  796. "excellon_update": True,
  797. "excellon_optimization_type": 'B',
  798. "excellon_search_time": 3,
  799. # Excellon Options
  800. "excellon_drillz": -0.0590551,
  801. "excellon_travelz": 0.0787402,
  802. "excellon_endz": 0.5,
  803. "excellon_feedrate": 3.14961,
  804. "excellon_spindlespeed": None,
  805. "excellon_dwell": False,
  806. "excellon_dwelltime": 1,
  807. "excellon_toolchange": False,
  808. "excellon_toolchangez": 0.5,
  809. "excellon_ppname_e": 'default',
  810. "excellon_tooldia": 0.0314961,
  811. "excellon_slot_tooldia": 0.0708661,
  812. "excellon_gcode_type": "drills",
  813. # Excellon Advanced Options
  814. "excellon_offset": 0.0,
  815. "excellon_toolchangexy": "0.0, 0.0",
  816. "excellon_startz": None,
  817. "excellon_feedrate_rapid": 31.4961,
  818. "excellon_z_pdepth": -0.02,
  819. "excellon_feedrate_probe": 3.14961,
  820. "excellon_spindledir": 'CW',
  821. "excellon_f_plunge": False,
  822. "excellon_f_retract": False,
  823. # Excellon Export
  824. "excellon_exp_units": 'INCH',
  825. "excellon_exp_format": 'ndec',
  826. "excellon_exp_integer": 2,
  827. "excellon_exp_decimals": 4,
  828. "excellon_exp_zeros": 'LZ',
  829. "excellon_exp_slot_type": 'routing',
  830. # Excellon Editor
  831. "excellon_editor_sel_limit": 30,
  832. "excellon_editor_newdia": 0.039,
  833. "excellon_editor_array_size": 5,
  834. "excellon_editor_lin_dir": 'X',
  835. "excellon_editor_lin_pitch": 0.1,
  836. "excellon_editor_lin_angle": 0.0,
  837. "excellon_editor_circ_dir": 'CW',
  838. "excellon_editor_circ_angle": 12,
  839. # Excellon Slots
  840. "excellon_editor_slot_direction": 'X',
  841. "excellon_editor_slot_angle": 0.0,
  842. "excellon_editor_slot_length": 5.0,
  843. # Excellon Slot Array
  844. "excellon_editor_slot_array_size": 5,
  845. "excellon_editor_slot_lin_dir": 'X',
  846. "excellon_editor_slot_lin_pitch": 0.1,
  847. "excellon_editor_slot_lin_angle": 0.0,
  848. "excellon_editor_slot_circ_dir": 'CW',
  849. "excellon_editor_slot_circ_angle": 0.0,
  850. # Geometry General
  851. "geometry_plot": True,
  852. "geometry_circle_steps": 128,
  853. "geometry_cnctooldia": "0.0944882",
  854. # Geometry Options
  855. "geometry_cutz": -0.0944882,
  856. "geometry_vtipdia": 0.1,
  857. "geometry_vtipangle": 30,
  858. "geometry_multidepth": False,
  859. "geometry_depthperpass": 0.0314961,
  860. "geometry_travelz": 0.0787402,
  861. "geometry_toolchange": False,
  862. "geometry_toolchangez": 0.5,
  863. "geometry_endz": 0.5,
  864. "geometry_feedrate": 3.14961,
  865. "geometry_feedrate_z": 3.14961,
  866. "geometry_spindlespeed": None,
  867. "geometry_dwell": False,
  868. "geometry_dwelltime": 1,
  869. "geometry_ppname_g": 'default',
  870. # Geometry Advanced Options
  871. "geometry_toolchangexy": "0.0, 0.0",
  872. "geometry_startz": None,
  873. "geometry_feedrate_rapid": 3.14961,
  874. "geometry_extracut": False,
  875. "geometry_z_pdepth": -0.02,
  876. "geometry_f_plunge": False,
  877. "geometry_spindledir": 'CW',
  878. "geometry_feedrate_probe": 3.14961,
  879. "geometry_segx": 0.0,
  880. "geometry_segy": 0.0,
  881. # Geometry Editor
  882. "geometry_editor_sel_limit": 30,
  883. # CNC Job General
  884. "cncjob_plot": True,
  885. "cncjob_plot_kind": 'all',
  886. "cncjob_annotation": True,
  887. "cncjob_tooldia": 0.0393701,
  888. "cncjob_coords_type": "G90",
  889. "cncjob_coords_decimals": 4,
  890. "cncjob_fr_decimals": 2,
  891. "cncjob_steps_per_circle": 128,
  892. # CNC Job Options
  893. "cncjob_prepend": "",
  894. "cncjob_append": "",
  895. # CNC Job Advanced Options
  896. "cncjob_toolchange_macro": "",
  897. "cncjob_toolchange_macro_enable": False,
  898. "cncjob_annotation_fontsize": 9,
  899. "cncjob_annotation_fontcolor": '#990000',
  900. # NCC Tool
  901. "tools_ncctools": "0.0393701, 0.019685",
  902. "tools_nccorder": 'rev',
  903. "tools_nccoverlap": 0.015748,
  904. "tools_nccmargin": 0.0393701,
  905. "tools_nccmethod": "seed",
  906. "tools_nccconnect": True,
  907. "tools_ncccontour": True,
  908. "tools_nccrest": False,
  909. "tools_ncc_offset_choice": False,
  910. "tools_ncc_offset_value": 0.0000,
  911. "tools_nccref": 'itself',
  912. "tools_ncc_plotting": 'normal',
  913. "tools_nccmilling_type": 'cl',
  914. "tools_ncctool_type": 'V',
  915. "tools_ncccutz": -0.001968504,
  916. "tools_ncctipdia": 0.00393701,
  917. "tools_ncctipangle": 30,
  918. # Cutout Tool
  919. "tools_cutouttooldia": 0.0944882,
  920. "tools_cutoutkind": "single",
  921. "tools_cutoutmargin": 0.00393701,
  922. "tools_cutoutgapsize": 0.15748,
  923. "tools_gaps_ff": "4",
  924. "tools_cutout_convexshape": False,
  925. # Paint Tool
  926. "tools_painttooldia": 0.023622,
  927. "tools_paintorder": 'rev',
  928. "tools_paintoverlap": 0.015748,
  929. "tools_paintmargin": 0.0,
  930. "tools_paintmethod": "seed",
  931. "tools_selectmethod": "single",
  932. "tools_pathconnect": True,
  933. "tools_paintcontour": True,
  934. "tools_paint_plotting": 'normal',
  935. # 2-Sided Tool
  936. "tools_2sided_mirror_axis": "X",
  937. "tools_2sided_axis_loc": "point",
  938. "tools_2sided_drilldia": 0.0393701,
  939. # Film Tool
  940. "tools_film_type": 'neg',
  941. "tools_film_boundary": 0.0393701,
  942. "tools_film_scale": 0,
  943. "tools_film_color": '#000000',
  944. # Panel Tool
  945. "tools_panelize_spacing_columns": 0,
  946. "tools_panelize_spacing_rows": 0,
  947. "tools_panelize_columns": 1,
  948. "tools_panelize_rows": 1,
  949. "tools_panelize_constrain": False,
  950. "tools_panelize_constrainx": 0.0,
  951. "tools_panelize_constrainy": 0.0,
  952. "tools_panelize_panel_type": 'gerber',
  953. # Calculators Tool
  954. "tools_calc_vshape_tip_dia": 0.007874,
  955. "tools_calc_vshape_tip_angle": 30,
  956. "tools_calc_vshape_cut_z": 0.000787,
  957. "tools_calc_electro_length": 10.0,
  958. "tools_calc_electro_width": 10.0,
  959. "tools_calc_electro_cdensity": 13.0,
  960. "tools_calc_electro_growth": 10.0,
  961. # Transform Tool
  962. "tools_transform_rotate": 90,
  963. "tools_transform_skew_x": 0.0,
  964. "tools_transform_skew_y": 0.0,
  965. "tools_transform_scale_x": 1.0,
  966. "tools_transform_scale_y": 1.0,
  967. "tools_transform_scale_link": True,
  968. "tools_transform_scale_reference": True,
  969. "tools_transform_offset_x": 0.0,
  970. "tools_transform_offset_y": 0.0,
  971. "tools_transform_mirror_reference": False,
  972. "tools_transform_mirror_point": (0, 0),
  973. # SolderPaste Tool
  974. "tools_solderpaste_tools": "0.0393701, 0.011811",
  975. "tools_solderpaste_new": 0.011811,
  976. "tools_solderpaste_z_start": 0.00019685039,
  977. "tools_solderpaste_z_dispense": 0.00393701,
  978. "tools_solderpaste_z_stop": 0.00019685039,
  979. "tools_solderpaste_z_travel": 0.00393701,
  980. "tools_solderpaste_z_toolchange": 0.0393701,
  981. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  982. "tools_solderpaste_frxy": 3.0,
  983. "tools_solderpaste_frz": 3.0,
  984. "tools_solderpaste_frz_dispense": 0.0393701,
  985. "tools_solderpaste_speedfwd": 20,
  986. "tools_solderpaste_dwellfwd": 1,
  987. "tools_solderpaste_speedrev": 10,
  988. "tools_solderpaste_dwellrev": 1,
  989. "tools_solderpaste_pp": 'Paste_1',
  990. # Subtract Tool
  991. "tools_sub_close_paths": True,
  992. # file associations
  993. "fa_excellon": ".drl, .xln, .drd, .tap, .exc, .ncd",
  994. "fa_gcode": ".nc, .ncc, .tap, .gcode, .cnc, .ecs, .fnc, .dnc, .ncg, .gc, .fan, .fgc, .din, .xpi,"
  995. " .hnc, .h, .i, .ncp, .min, .gcd, .rol, .mpr, .ply, .out, .eia, .plt, .sbp, .mpf",
  996. "fa_gerber": ".gbr, .ger, .gtl, .gbl, .gts, .gbs, .gtp, .gbp, .gto, .gbo, .gm1, .gml, .gm3, .gko, .cmp, "
  997. ".sol, .stc, .sts, .plc, .pls, .crc, .crs, .tsm, .bsm, .ly2, .ly15, .dim, .mil, .grb, .top, "
  998. ".bot, .smt, .smb, .sst, .ssb, .spt, .spb, .pho, .gdo, .art, .gbd",
  999. })
  1000. # ############################################################
  1001. # ############### Load defaults from file ####################
  1002. # ############################################################
  1003. if user_defaults:
  1004. self.load_defaults(filename='current_defaults')
  1005. # #############################################################
  1006. # ############## APPLY APP LANGUAGE ###########################
  1007. # #############################################################
  1008. ret_val = fcTranslate.apply_language('strings')
  1009. if ret_val == "no language":
  1010. self.inform.emit('[ERROR] %s' %
  1011. _("Could not find the Language files. The App strings are missing."))
  1012. log.debug("Could not find the Language files. The App strings are missing.")
  1013. else:
  1014. # make the current language the current selection on the language combobox
  1015. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1016. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1017. # ##############################################################
  1018. # ################# CREATE UNIQUE SERIAL NUMBER ################
  1019. # ##############################################################
  1020. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1021. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1022. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  1023. self.save_defaults(silent=True)
  1024. self.propagate_defaults(silent=True)
  1025. self.restore_main_win_geom()
  1026. def auto_save_defaults():
  1027. try:
  1028. self.save_defaults(silent=True)
  1029. self.propagate_defaults(silent=True)
  1030. finally:
  1031. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1032. # the following lines activates automatic defaults save
  1033. # if user_defaults:
  1034. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1035. # self.options_form = PreferencesUI()
  1036. self.options_form_fields = {
  1037. "units": self.ui.general_options_form.general_app_group.units_radio,
  1038. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1039. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1040. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1041. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1042. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1043. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1044. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1045. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1046. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1047. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1048. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1049. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1050. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1051. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1052. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1053. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1054. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1055. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1056. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1057. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1058. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1059. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1060. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1061. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1062. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1063. "excellon_endz": self.ui.excellon_options_form.excellon_opt_group.eendz_entry,
  1064. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1065. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1066. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1067. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1068. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1069. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1070. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1071. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1072. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1073. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1074. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1075. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1076. "excellon_spindledir": self.ui.excellon_options_form.excellon_adv_opt_group.spindledir_radio,
  1077. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1078. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1079. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1080. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1081. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1082. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1083. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1084. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1085. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1086. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1087. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1088. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1089. "geometry_endz": self.ui.geometry_options_form.geometry_opt_group.gendz_entry,
  1090. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1091. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1092. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1093. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1094. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1095. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1096. "geometry_spindledir": self.ui.geometry_options_form.geometry_adv_opt_group.spindledir_radio,
  1097. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1098. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1099. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1100. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1101. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1102. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1103. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1104. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1105. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1106. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1107. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1108. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1109. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1110. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1111. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1112. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1113. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1114. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1115. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1116. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1117. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1118. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1119. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1120. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1121. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1122. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1123. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1124. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1125. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1126. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1127. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1128. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1129. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1130. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1131. }
  1132. for name in list(self.postprocessors.keys()):
  1133. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1134. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1135. self.options = LoudDict()
  1136. self.options.set_change_callback(self.on_options_dict_change)
  1137. self.options.update({
  1138. "units": "IN",
  1139. "global_gridx": 1.0,
  1140. "global_gridy": 1.0,
  1141. "global_snap_max": 0.05,
  1142. "global_background_timeout": 300000, # Default value is 5 minutes
  1143. "global_verbose_error_level": 0, # Shell verbosity:
  1144. # 0 = default(python trace only for unknown errors),
  1145. # 1 = show trace(show trace allways), 2 = (For the future).
  1146. "gerber_plot": True,
  1147. "gerber_solid": True,
  1148. "gerber_multicolored": False,
  1149. "gerber_isotooldia": 0.016,
  1150. "gerber_isopasses": 1,
  1151. "gerber_isooverlap": 0.15,
  1152. "gerber_combine_passes": True,
  1153. "gerber_noncoppermargin": 0.0,
  1154. "gerber_noncopperrounded": False,
  1155. "gerber_bboxmargin": 0.0,
  1156. "gerber_bboxrounded": False,
  1157. "excellon_plot": True,
  1158. "excellon_solid": False,
  1159. "excellon_format_upper_in": 2,
  1160. "excellon_format_lower_in": 4,
  1161. "excellon_format_upper_mm": 3,
  1162. "excellon_format_lower_mm": 3,
  1163. "excellon_units": 'INCH',
  1164. "excellon_optimization_type": 'B',
  1165. "excellon_search_time": 3,
  1166. "excellon_zeros": "L",
  1167. "excellon_drillz": -0.1,
  1168. "excellon_travelz": 0.1,
  1169. "excellon_feedrate": 3.0,
  1170. "excellon_feedrate_rapid": 3.0,
  1171. "excellon_spindlespeed": None,
  1172. "excellon_spindledir": 'CW',
  1173. "excellon_dwell": True,
  1174. "excellon_dwelltime": 1000,
  1175. "excellon_toolchange": False,
  1176. "excellon_toolchangez": 1.0,
  1177. "excellon_toolchangexy": "0.0, 0.0",
  1178. "excellon_tooldia": 0.016,
  1179. "excellon_ppname_e": 'default',
  1180. "excellon_f_plunge": False,
  1181. "excellon_startz": None,
  1182. "excellon_endz": 2.0,
  1183. "geometry_plot": True,
  1184. "geometry_segx": 0.0,
  1185. "geometry_segy": 0.0,
  1186. "geometry_cutz": -0.002,
  1187. "geometry_vtipdia": 0.1,
  1188. "geometry_vtipangle": 30,
  1189. "geometry_travelz": 0.1,
  1190. "geometry_feedrate": 3.0,
  1191. "geometry_feedrate_z": 3.0,
  1192. "geometry_feedrate_rapid": 3.0,
  1193. "geometry_spindlespeed": None,
  1194. "geometry_spindledir": 'CW',
  1195. "geometry_dwell": True,
  1196. "geometry_dwelltime": 1000,
  1197. "geometry_cnctooldia": 0.016,
  1198. "geometry_toolchange": False,
  1199. "geometry_toolchangez": 2.0,
  1200. "geometry_toolchangexy": "0.0, 0.0",
  1201. "geometry_startz": None,
  1202. "geometry_endz": 2.0,
  1203. "geometry_ppname_g": "default",
  1204. "geometry_f_plunge": False,
  1205. "geometry_depthperpass": 0.002,
  1206. "geometry_multidepth": False,
  1207. "geometry_extracut": False,
  1208. "cncjob_plot": True,
  1209. "cncjob_tooldia": 0.016,
  1210. "cncjob_prepend": "",
  1211. "cncjob_append": "",
  1212. "tools_ncctools": "1.0, 0.5",
  1213. "tools_nccoverlap": 0.4,
  1214. "tools_nccmargin": 1,
  1215. "tools_cutouttooldia": 0.07,
  1216. "tools_cutoutmargin": 0.1,
  1217. "tools_cutoutgapsize": 0.15,
  1218. "tools_gaps_ff": "8",
  1219. "tools_painttooldia": 0.07,
  1220. "tools_paintoverlap": 0.15,
  1221. "tools_paintmargin": 0.0,
  1222. "tools_paintmethod": "seed",
  1223. "tools_selectmethod": "single",
  1224. "tools_pathconnect": True,
  1225. "tools_paintcontour": True,
  1226. "tools_2sided_mirror_axis": "X",
  1227. "tools_2sided_axis_loc": 'point',
  1228. "tools_2sided_drilldia": 1,
  1229. "tools_film_type": 'neg',
  1230. "tools_film_boundary": 1,
  1231. "tools_film_scale": 0,
  1232. "tools_panelize_spacing_columns": 0,
  1233. "tools_panelize_spacing_rows": 0,
  1234. "tools_panelize_columns": 1,
  1235. "tools_panelize_rows": 1,
  1236. "tools_panelize_constrain": False,
  1237. "tools_panelize_constrainx": 0.0,
  1238. "tools_panelize_constrainy": 0.0
  1239. })
  1240. self.options.update(self.defaults) # Copy app defaults to project options
  1241. self.gen_form = None
  1242. self.ger_form = None
  1243. self.exc_form = None
  1244. self.geo_form = None
  1245. self.cnc_form = None
  1246. self.tools_form = None
  1247. self.fa_form = None
  1248. self.on_options_combo_change(0) # Will show the initial form
  1249. # ################################
  1250. # ### Initialize the color box's color in Preferences -> Global -> Color
  1251. # Init Plot Colors
  1252. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1253. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1254. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1255. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1256. int(self.defaults['global_plot_fill'][7:9], 16))
  1257. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1258. int(self.defaults['global_plot_fill'][7:9], 16))
  1259. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1260. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1261. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1262. # Init Left-Right Selection colors
  1263. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1264. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1265. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1266. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1267. int(self.defaults['global_sel_fill'][7:9], 16))
  1268. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1269. int(self.defaults['global_sel_fill'][7:9], 16))
  1270. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1271. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1272. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1273. # Init Right-Left Selection colors
  1274. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1275. self.defaults['global_alt_sel_fill'])
  1276. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1277. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1278. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1279. int(self.defaults['global_sel_fill'][7:9], 16))
  1280. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1281. int(self.defaults['global_sel_fill'][7:9], 16))
  1282. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1283. self.defaults['global_alt_sel_line'])
  1284. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1285. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1286. # Init Draw color and Selection Draw Color
  1287. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1288. self.defaults['global_draw_color'])
  1289. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1290. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1291. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1292. self.defaults['global_sel_draw_color'])
  1293. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1294. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1295. # Init Project Items color
  1296. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1297. self.defaults['global_proj_item_color'])
  1298. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1299. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1300. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1301. self.defaults['global_proj_item_dis_color'])
  1302. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1303. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1304. # Init the Annotation CNC Job color
  1305. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  1306. self.defaults['cncjob_annotation_fontcolor'])
  1307. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  1308. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1309. # Init the Tool Film color
  1310. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  1311. self.defaults['tools_film_color'])
  1312. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  1313. "background-color:%s" % str(self.defaults['tools_film_color'])[:7])
  1314. # ### End of Data ####
  1315. # ###############################################
  1316. # ############# SETUP Plot Area #################
  1317. # ###############################################
  1318. if show_splash:
  1319. splash.showMessage(_("FlatCAM is initializing ...\n"
  1320. "Canvas initialization started."),
  1321. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1322. color=QtGui.QColor("gray"))
  1323. start_plot_time = time.time() # debug
  1324. self.plotcanvas = None
  1325. self.app_cursor = None
  1326. self.hover_shapes = None
  1327. self.on_plotcanvas_setup()
  1328. end_plot_time = time.time()
  1329. used_time = end_plot_time - start_plot_time
  1330. self.log.debug("Finished Canvas initialization in %s seconds." % str(used_time))
  1331. if show_splash:
  1332. splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1333. "Canvas initialization started.\n"
  1334. "Canvas initialization finished in"), '%.2f' % used_time),
  1335. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1336. color=QtGui.QColor("gray"))
  1337. self.ui.splitter.setStretchFactor(1, 2)
  1338. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1339. # depending on from where those tools are called different actions can be done
  1340. self.call_source = 'app'
  1341. # ##############################################
  1342. # ######### SETUP OBJECT COLLECTION ############
  1343. # ##############################################
  1344. self.collection = ObjectCollection(self)
  1345. self.ui.project_tab_layout.addWidget(self.collection.view)
  1346. # ### Adjust tabs width ## ##
  1347. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1348. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1349. self.collection.view.setMinimumWidth(290)
  1350. self.log.debug("Finished creating Object Collection.")
  1351. # ###############################################
  1352. # ############# Worker SETUP ####################
  1353. # ###############################################
  1354. if self.defaults["global_worker_number"]:
  1355. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1356. else:
  1357. self.workers = WorkerStack(workers_number=2)
  1358. self.worker_task.connect(self.workers.add_task)
  1359. self.log.debug("Finished creating Workers crew.")
  1360. # ################################################
  1361. # ############### Signal handling ################
  1362. # ################################################
  1363. # ############# Custom signals ##################
  1364. # signal for displaying messages in status bar
  1365. self.inform.connect(self.info)
  1366. # signal to be called when the app is quiting
  1367. self.app_quit.connect(self.quit_application)
  1368. self.message.connect(self.message_dialog)
  1369. self.progress.connect(self.set_progress_bar)
  1370. # signals that are emitted when object state changes
  1371. self.object_created.connect(self.on_object_created)
  1372. self.object_changed.connect(self.on_object_changed)
  1373. self.object_plotted.connect(self.on_object_plotted)
  1374. self.plots_updated.connect(self.on_plots_updated)
  1375. # signals emitted when file state change
  1376. self.file_opened.connect(self.register_recent)
  1377. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1378. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1379. # ############# Standard signals ###################
  1380. # ### Menu
  1381. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1382. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1383. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1384. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1385. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1386. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1387. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1388. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1389. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1390. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1391. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1392. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1393. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1394. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1395. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1396. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1397. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1398. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1399. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1400. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1401. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1402. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1403. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1404. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1405. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1406. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1407. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1408. self.ui.menufile_exit.triggered.connect(self.final_save)
  1409. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1410. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1411. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1412. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1413. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1414. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1415. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1416. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1417. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1418. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1419. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1420. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1421. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1422. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1423. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1424. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1425. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1426. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1427. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1428. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1429. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1430. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1431. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1432. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1433. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1434. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1435. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1436. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1437. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1438. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1439. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1440. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1441. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1442. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1443. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1444. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1445. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1446. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1447. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1448. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1449. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1450. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1451. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1452. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1453. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1454. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1455. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1456. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1457. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1458. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1459. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1460. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1461. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1462. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1463. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1464. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1465. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1466. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1467. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1468. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1469. # ToolBar signals
  1470. self.connect_toolbar_signals()
  1471. # Notebook signals
  1472. # make the right click on the notebook tab connect to a function
  1473. self.ui.notebook.setupContextMenu()
  1474. self.ui.notebook.addContextMenu(
  1475. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1476. initial_checked=self.defaults["global_tabs_detachable"])
  1477. # activate initial state
  1478. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1479. # Context Menu
  1480. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1481. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1482. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1483. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1484. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1485. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1486. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1487. self.ui.clearplot.triggered.connect(self.clear_plots)
  1488. self.ui.replot.triggered.connect(self.plot_all)
  1489. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1490. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1491. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1492. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1493. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1494. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1495. # Preferences Plot Area TAB
  1496. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1497. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1498. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1499. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1500. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1501. # ##############################
  1502. # ### GUI PREFERENCES SIGNALS ##
  1503. # ##############################
  1504. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1505. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1506. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1507. )
  1508. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1509. lambda: self.on_toggle_units(no_pref=False))
  1510. # ###############################################################
  1511. # ################### GUI COLORS SIGNALS ########################
  1512. # ###############################################################
  1513. # Setting plot colors signals
  1514. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1515. self.on_pf_color_entry)
  1516. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1517. self.on_pf_color_button)
  1518. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1519. self.on_pf_color_spinner)
  1520. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1521. self.on_pf_color_slider)
  1522. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1523. self.on_pl_color_entry)
  1524. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1525. self.on_pl_color_button)
  1526. # Setting selection (left - right) colors signals
  1527. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1528. self.on_sf_color_entry)
  1529. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1530. self.on_sf_color_button)
  1531. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1532. self.on_sf_color_spinner)
  1533. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1534. self.on_sf_color_slider)
  1535. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1536. self.on_sl_color_entry)
  1537. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1538. self.on_sl_color_button)
  1539. # Setting selection (right - left) colors signals
  1540. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1541. self.on_alt_sf_color_entry)
  1542. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1543. self.on_alt_sf_color_button)
  1544. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1545. self.on_alt_sf_color_spinner)
  1546. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1547. self.on_alt_sf_color_slider)
  1548. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1549. self.on_alt_sl_color_entry)
  1550. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1551. self.on_alt_sl_color_button)
  1552. # Setting Editor Draw colors signals
  1553. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1554. self.on_draw_color_entry)
  1555. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1556. self.on_draw_color_button)
  1557. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1558. self.on_sel_draw_color_entry)
  1559. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1560. self.on_sel_draw_color_button)
  1561. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1562. self.on_proj_color_entry)
  1563. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1564. self.on_proj_color_button)
  1565. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1566. self.on_proj_color_dis_entry)
  1567. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1568. self.on_proj_color_dis_button)
  1569. # ########## workspace setting signals ###########
  1570. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1571. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1572. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1573. # ########## CNC Job related signals #############
  1574. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1575. self.on_cnc_custom_parameters)
  1576. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1577. self.on_annotation_fontcolor_entry)
  1578. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1579. self.on_annotation_fontcolor_button)
  1580. # ########## Tools related signals #############
  1581. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1582. self.on_film_color_entry)
  1583. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1584. self.on_film_color_button)
  1585. # ########## Modify G-CODE Plot Area TAB ###########
  1586. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1587. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1588. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1589. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1590. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1591. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1592. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1593. # portability changed signal
  1594. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1595. # Object list
  1596. self.collection.view.activated.connect(self.on_row_activated)
  1597. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1598. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1599. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1600. # Export Excellon parameters.
  1601. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1602. self.on_update_exc_export
  1603. )
  1604. # call it once to make sure it is updated at startup
  1605. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1606. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1607. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1608. self.on_excellon_defaults_button)
  1609. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1610. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1611. self.on_excellon_options_button)
  1612. # when there are arguments at application startup this get launched
  1613. self.args_at_startup[list].connect(lambda: self.on_startup_args())
  1614. # connect the 'Apply' buttons from the Preferences/File Associations
  1615. self.ui.fa_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1616. lambda: self.on_register_files(obj_type='excellon'))
  1617. self.ui.fa_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1618. lambda: self.on_register_files(obj_type='gcode'))
  1619. self.ui.fa_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1620. lambda: self.on_register_files(obj_type='gerber'))
  1621. # splash screen button signal
  1622. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1623. # connect the abort_all_tasks related slots to the related signals
  1624. self.proc_container.idle_flag.connect(self.app_is_idle)
  1625. # #####################################################################################
  1626. # ########### FINISHED CONNECTING SIGNALS #############################################
  1627. # #####################################################################################
  1628. self.log.debug("Finished connecting Signals.")
  1629. # #####################################################################################
  1630. # ########################## Other setups #############################################
  1631. # #####################################################################################
  1632. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1633. self.tool_tab_locked = False
  1634. # decide if to show or hide the Notebook side of the screen at startup
  1635. if self.defaults["global_project_at_startup"] is True:
  1636. self.ui.splitter.setSizes([1, 1])
  1637. else:
  1638. self.ui.splitter.setSizes([0, 1])
  1639. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1640. self.setup_obj_classes()
  1641. self.setup_recent_items()
  1642. self.setup_component_editor()
  1643. # #####################################################################################
  1644. # ######################### Auto-complete KEYWORDS ####################################
  1645. # #####################################################################################
  1646. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1647. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1648. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1649. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1650. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1651. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1652. 'mirror', 'ncc',
  1653. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1654. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'paint',
  1655. 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'save', 'save_project',
  1656. 'save_sys', 'scale',
  1657. 'set_active', 'set_sys', 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1658. 'version', 'write_gcode'
  1659. ]
  1660. self.ordinary_keywords = self.defaults["global_autocomplete_keywords"]
  1661. self.tcl_keywords = [
  1662. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1663. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1664. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1665. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1666. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1667. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1668. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1669. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1670. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1671. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1672. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1673. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1674. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1675. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1676. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1677. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1678. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1679. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1680. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1681. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1682. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1683. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1684. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1685. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1686. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1687. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1688. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1689. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1690. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1691. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1692. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1693. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1694. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1695. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1696. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1697. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1698. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1699. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1700. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1701. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1702. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1703. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1704. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1705. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1706. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1707. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1708. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1709. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1710. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1711. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1712. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1713. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1714. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1715. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1716. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1717. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1718. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1719. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1720. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1721. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1722. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1723. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1724. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1725. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1726. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1727. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1728. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1729. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1730. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1731. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1732. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1733. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1734. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1735. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1736. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1737. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1738. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1739. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1740. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1741. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1742. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1743. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1744. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1745. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1746. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1747. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1748. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1749. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1750. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1751. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1752. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1753. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1754. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1755. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1756. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1757. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1758. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1759. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1760. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1761. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1762. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1763. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1764. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1765. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1766. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1767. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1768. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1769. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1770. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1771. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1772. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1773. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1774. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1775. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1776. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1777. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1778. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1779. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1780. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1781. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1782. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1783. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1784. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1785. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1786. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1787. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1788. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1789. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1790. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1791. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1792. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1793. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1794. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1795. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1796. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1797. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1798. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1799. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1800. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1801. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1802. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1803. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1804. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1805. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1806. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1807. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1808. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1809. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1810. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1811. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1812. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1813. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1814. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1815. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1816. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1817. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1818. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1819. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1820. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1821. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1822. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1823. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1824. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1825. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1826. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1827. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1828. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1829. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1830. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1831. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1832. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1833. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1834. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1835. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1836. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1837. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1838. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1839. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1840. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1841. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1842. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1843. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1844. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1845. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1846. ]
  1847. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords + self.tcl_keywords
  1848. self.default_autocomplete_keywords = [
  1849. 'all', 'angle_x', 'angle_y', 'axis', 'axisoffset', 'box', 'center_x', 'center_y',
  1850. 'columns', 'combine', 'connect', 'contour', 'depthperpass', 'dia', 'diatol', 'dist',
  1851. 'drilled_dias', 'drillz', 'pp',
  1852. 'gridoffsety', 'gridx', 'gridy', 'has_offset', 'holes', 'margin', 'method',
  1853. 'milled_dias',
  1854. 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order', 'outname',
  1855. 'overlap', 'passes', 'postamble', 'ppname_e', 'ppname_g', 'preamble', 'radius', 'ref',
  1856. 'rest', 'rows', 'scale_factor', 'spacing_columns', 'spacing_rows', 'spindlespeed',
  1857. 'use_threads', 'value', 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move',
  1858. 'default', 'feedrate_z', 'grbl_11', 'grbl_laser', 'hpgl', 'line_xyz', 'marlin',
  1859. 'Paste_1', 'Repetier', 'Toolchange_Custom', 'Roland_MDX_20', 'Toolchange_manual',
  1860. 'Toolchange_Probe_MACH3', 'dwell', 'dwelltime', 'toolchange_xy', 'iso_type',
  1861. 'Desktop', 'FlatPrj', 'FlatConfig', 'Users', 'Documents', 'My Documents', 'Marius'
  1862. ]
  1863. # ####################################################################################
  1864. # ####################### Shell SETUP ################################################
  1865. # ####################################################################################
  1866. self.shell = FCShell(self, version=self.version)
  1867. self.shell._edit.set_model_data(self.myKeywords)
  1868. self.ui.code_editor.set_model_data(self.myKeywords)
  1869. self.shell.setWindowIcon(self.ui.app_icon)
  1870. self.shell.setWindowTitle("FlatCAM Shell")
  1871. self.shell.resize(*self.defaults["global_shell_shape"])
  1872. self.shell.append_output("FlatCAM %s - " % self.version)
  1873. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  1874. self.init_tcl()
  1875. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1876. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1877. self.ui.shell_dock.setWidget(self.shell)
  1878. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1879. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1880. QtWidgets.QDockWidget.DockWidgetFloatable |
  1881. QtWidgets.QDockWidget.DockWidgetClosable)
  1882. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1883. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1884. if self.defaults["global_shell_at_startup"]:
  1885. self.ui.shell_dock.show()
  1886. else:
  1887. self.ui.shell_dock.hide()
  1888. # ##################################################################################
  1889. # ###################### Tools and Plugins #########################################
  1890. # ##################################################################################
  1891. self.dblsidedtool = None
  1892. self.measurement_tool = None
  1893. self.panelize_tool = None
  1894. self.film_tool = None
  1895. self.paste_tool = None
  1896. self.calculator_tool = None
  1897. self.sub_tool = None
  1898. self.move_tool = None
  1899. self.cutout_tool = None
  1900. self.ncclear_tool = None
  1901. self.paint_tool = None
  1902. self.transform_tool = None
  1903. self.properties_tool = None
  1904. self.pdf_tool = None
  1905. self.image_tool = None
  1906. self.pcb_wizard_tool = None
  1907. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1908. self.install_tools()
  1909. # ### System Font Parsing ###
  1910. # self.f_parse = ParseFont(self)
  1911. # self.parse_system_fonts()
  1912. # #####################################################################################
  1913. # ########################## START-UP ARGUMENTS #######################################
  1914. # #####################################################################################
  1915. # test if the program was started with a script as parameter
  1916. if self.cmd_line_shellfile:
  1917. try:
  1918. with open(self.cmd_line_shellfile, "r") as myfile:
  1919. cmd_line_shellfile_text = myfile.read()
  1920. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1921. except Exception as ext:
  1922. print("ERROR: ", ext)
  1923. sys.exit(2)
  1924. # #####################################################################################
  1925. # ######################## Check for updates ##########################################
  1926. # #####################################################################################
  1927. # Separate thread (Not worker)
  1928. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1929. if (self.beta is False or self.beta is None) and \
  1930. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1931. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1932. self.thr2 = QtCore.QThread()
  1933. self.worker_task.emit({'fcn': self.version_check,
  1934. 'params': []})
  1935. self.thr2.start(QtCore.QThread.LowPriority)
  1936. # #####################################################################################
  1937. # ###################### Variables for global usage ###################################
  1938. # #####################################################################################
  1939. # register files with FlatCAM; it works only for Windows for now
  1940. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1941. self.on_register_files()
  1942. # coordinates for relative position display
  1943. self.rel_point1 = (0, 0)
  1944. self.rel_point2 = (0, 0)
  1945. # variable to store coordinates
  1946. self.pos = (0, 0)
  1947. self.pos_jump = (0, 0)
  1948. # variable to store mouse coordinates
  1949. self.mouse = [0, 0]
  1950. # decide if we have a double click or single click
  1951. self.doubleclick = False
  1952. # variable to store if a command is active (then the var is not None) and which one it is
  1953. self.command_active = None
  1954. # variable to store the status of moving selection action
  1955. # None value means that it's not an selection action
  1956. # True value = a selection from left to right
  1957. # False value = a selection from right to left
  1958. self.selection_type = None
  1959. # List to store the objects that are currently loaded in FlatCAM
  1960. # This list is updated on each object creation or object delete
  1961. self.all_objects_list = []
  1962. # List to store the objects that are selected
  1963. self.sel_objects_list = []
  1964. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1965. self.key_modifiers = None
  1966. # Variable to hold the status of the axis
  1967. self.toggle_axis = True
  1968. # Variable to store the status of the fullscreen event
  1969. self.toggle_fscreen = False
  1970. # Variable to store the status of the code editor
  1971. self.toggle_codeeditor = False
  1972. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1973. self.click_noproject = False
  1974. self.cursor = None
  1975. # Variable to store the GCODE that was edited
  1976. self.gcode_edited = ""
  1977. # reference for the self.ui.code_editor
  1978. self.reference_code_editor = None
  1979. self.script_code = ''
  1980. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  1981. self.preferences_changed_flag = False
  1982. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3',
  1983. 'gko', 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15',
  1984. 'dim', 'mil', 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo',
  1985. 'art', 'gbd', 'gb0', 'gb1', 'gb2', 'gb3', 'g4', 'gb5', 'gb6', 'gb7', 'gb8', 'gb9'
  1986. ]
  1987. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc', 'ncd']
  1988. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1989. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1990. 'mpf'
  1991. ]
  1992. self.svg_list = ['svg']
  1993. self.dxf_list = ['dxf']
  1994. self.pdf_list = ['pdf']
  1995. self.prj_list = ['flatprj']
  1996. self.conf_list = ['flatconfig']
  1997. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1998. # flag for polygons not cleared
  1999. self.poly_not_cleared = False
  2000. # VisPy visuals
  2001. self.isHovering = False
  2002. self.notHovering = True
  2003. # when True, the app has to return from any thread
  2004. self.abort_flag = False
  2005. # ###############################################################################
  2006. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2007. # ############# It's done only once after install ###############
  2008. # ###############################################################################
  2009. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2010. fac_def_from_file = factory_file.read()
  2011. factory_defaults = json.loads(fac_def_from_file)
  2012. # if the file contain an empty dictionary then save the factory defaults into the file
  2013. if not factory_defaults:
  2014. self.save_factory_defaults(silent=False)
  2015. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2016. initial_lay = 'compact'
  2017. self.on_layout(lay=initial_lay)
  2018. # Set the combobox in Preferences to the current layout
  2019. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2020. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2021. factory_file.close()
  2022. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2023. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2024. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2025. # after the first run, this object should be False
  2026. self.defaults["first_run"] = False
  2027. # ###############################################################################
  2028. # ################# ADDING FlatCAM EDITORS section ##############################
  2029. # ###############################################################################
  2030. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2031. # at the first launch of the App , the editors will not be functional.
  2032. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2033. self.exc_editor = FlatCAMExcEditor(self)
  2034. self.grb_editor = FlatCAMGrbEditor(self)
  2035. self.log.debug("Finished adding FlatCAM Editor's.")
  2036. self.set_ui_title(name=_("New Project - Not saved"))
  2037. # finish the splash
  2038. # splash.finish(self.ui)
  2039. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2040. current_platform = platform.architecture()[0]
  2041. if current_platform != '64bit':
  2042. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2043. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2044. # ###############################################################################
  2045. # ####################### Finished the CONSTRUCTOR ##############################
  2046. # ###############################################################################
  2047. App.log.debug("END of constructor. Releasing control.")
  2048. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2049. # the path/file_name must be enclosed in quotes if it contain spaces
  2050. if App.args:
  2051. self.args_at_startup.emit(App.args)
  2052. @staticmethod
  2053. def copy_and_overwrite(from_path, to_path):
  2054. """
  2055. From here:
  2056. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2057. :param from_path: source path
  2058. :param to_path: destination path
  2059. :return: None
  2060. """
  2061. if os.path.exists(to_path):
  2062. shutil.rmtree(to_path)
  2063. try:
  2064. shutil.copytree(from_path, to_path)
  2065. except FileNotFoundError:
  2066. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2067. shutil.copytree(from_new_path, to_path)
  2068. def on_startup_args(self, args=None):
  2069. """
  2070. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2071. :param args: a list containing the application args at startup
  2072. :return: None
  2073. """
  2074. if args:
  2075. args_to_process = args
  2076. else:
  2077. args_to_process = App.args
  2078. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2079. for argument in args_to_process:
  2080. if '.FlatPrj' in argument:
  2081. try:
  2082. project_name = str(argument)
  2083. if project_name == "":
  2084. self.inform.emit(_("Open cancelled."))
  2085. else:
  2086. # self.open_project(project_name)
  2087. run_from_arg = True
  2088. # self.worker_task.emit({'fcn': self.open_project,
  2089. # 'params': [project_name, run_from_arg]})
  2090. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2091. except Exception as e:
  2092. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2093. elif '.FlatConfig' in argument:
  2094. try:
  2095. file_name = str(argument)
  2096. if file_name == "":
  2097. self.inform.emit(_("Open Config file failed."))
  2098. else:
  2099. # run_from_arg = True
  2100. # self.worker_task.emit({'fcn': self.open_config_file,
  2101. # 'params': [file_name, run_from_arg]})
  2102. self.open_config_file(file_name, run_from_arg=True)
  2103. except Exception as e:
  2104. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2105. elif '.FlatScript' in argument:
  2106. try:
  2107. file_name = str(argument)
  2108. if file_name == "":
  2109. self.inform.emit(_("Open Script file failed."))
  2110. else:
  2111. # run_from_arg = True
  2112. # self.worker_task.emit({'fcn': self.open_script_file,
  2113. # 'params': [file_name, run_from_arg]})
  2114. self.on_filerunscript(name=file_name)
  2115. except Exception as e:
  2116. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2117. else:
  2118. exc_list = self.ui.fa_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2119. proc_arg = argument.lower()
  2120. for ext in exc_list:
  2121. proc_ext = ext.replace(' ', '')
  2122. if proc_ext.lower() in proc_arg and proc_ext != '':
  2123. file_name = str(argument)
  2124. if file_name == "":
  2125. self.inform.emit(_("Open Excellon file failed."))
  2126. else:
  2127. self.on_fileopenexcellon(name=file_name)
  2128. return
  2129. gco_list = self.ui.fa_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2130. for ext in gco_list:
  2131. proc_ext = ext.replace(' ', '')
  2132. if proc_ext.lower() in proc_arg and proc_ext != '':
  2133. file_name = str(argument)
  2134. if file_name == "":
  2135. self.inform.emit(_("Open GCode file failed."))
  2136. else:
  2137. self.on_fileopengcode(name=file_name)
  2138. return
  2139. grb_list = self.ui.fa_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2140. for ext in grb_list:
  2141. proc_ext = ext.replace(' ', '')
  2142. if proc_ext.lower() in proc_arg and proc_ext != '':
  2143. file_name = str(argument)
  2144. if file_name == "":
  2145. self.inform.emit(_("Open Gerber file failed."))
  2146. else:
  2147. self.on_fileopengerber(name=file_name)
  2148. return
  2149. def set_ui_title(self, name):
  2150. """
  2151. Sets the title of the main window.
  2152. :param name: String that store the project path and project name
  2153. :return: None
  2154. """
  2155. self.ui.setWindowTitle('FlatCAM %s %s - %s %s' %
  2156. (self.version,
  2157. ('BETA' if self.beta else ''),
  2158. platform.architecture()[0],
  2159. name)
  2160. )
  2161. def defaults_read_form(self):
  2162. """
  2163. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2164. :return: None
  2165. """
  2166. for option in self.defaults_form_fields:
  2167. try:
  2168. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2169. except Exception as e:
  2170. log.debug("App.defaults_read_form() --> %s" % str(e))
  2171. def defaults_write_form(self, factor=None, fl_units=None):
  2172. """
  2173. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2174. self.defaults dictionary.
  2175. :param factor: will apply a factor to the values that written in the GUI elements
  2176. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2177. :return: None
  2178. """
  2179. for option in self.defaults:
  2180. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2181. # try:
  2182. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2183. # except KeyError:
  2184. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2185. # # TODO: Rethink this?
  2186. # pass
  2187. def defaults_write_form_field(self, field, factor=None, units=None):
  2188. """
  2189. Basically it is the worker in the self.defaults_write_form()
  2190. :param field: the GUI element in Preferences GUI to be updated
  2191. :param factor: factor to be applied to the field parameter
  2192. :param units: current FLatCAM measuring units
  2193. :return: None, it updates GUI elements
  2194. """
  2195. try:
  2196. if factor is None:
  2197. if units is None:
  2198. self.defaults_form_fields[field].set_value(self.defaults[field])
  2199. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2200. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2201. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2202. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2203. else:
  2204. if units is None:
  2205. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2206. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2207. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2208. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2209. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2210. except KeyError:
  2211. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2212. # TODO: Rethink this?
  2213. pass
  2214. except AttributeError:
  2215. log.debug(field)
  2216. def clear_pool(self):
  2217. """
  2218. Clear the multiprocessing pool and calls garbage collector.
  2219. :return: None
  2220. """
  2221. self.pool.close()
  2222. self.pool = Pool()
  2223. self.pool_recreated.emit(self.pool)
  2224. gc.collect()
  2225. def install_tools(self):
  2226. """
  2227. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2228. Instantiation of the Tools classes.
  2229. The order that the tools are installed is important as they can depend on each other install position.
  2230. :return: None
  2231. """
  2232. self.dblsidedtool = DblSidedTool(self)
  2233. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2234. self.measurement_tool = Measurement(self)
  2235. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  2236. self.panelize_tool = Panelize(self)
  2237. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2238. self.film_tool = Film(self)
  2239. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2240. self.paste_tool = SolderPaste(self)
  2241. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2242. self.calculator_tool = ToolCalculator(self)
  2243. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2244. self.sub_tool = ToolSub(self)
  2245. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2246. self.move_tool = ToolMove(self)
  2247. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2248. before=self.ui.menueditorigin)
  2249. self.cutout_tool = CutOut(self)
  2250. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2251. before=self.measurement_tool.menuAction)
  2252. self.ncclear_tool = NonCopperClear(self)
  2253. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2254. before=self.measurement_tool.menuAction, separator=True)
  2255. self.paint_tool = ToolPaint(self)
  2256. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2257. before=self.measurement_tool.menuAction, separator=True)
  2258. self.transform_tool = ToolTransform(self)
  2259. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2260. self.properties_tool = Properties(self)
  2261. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2262. self.pdf_tool = ToolPDF(self)
  2263. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2264. separator=True)
  2265. self.image_tool = ToolImage(self)
  2266. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2267. separator=True)
  2268. self.pcb_wizard_tool = PcbWizard(self)
  2269. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2270. self.log.debug("Tools are installed.")
  2271. def remove_tools(self):
  2272. """
  2273. Will remove all the actions in the Tool menu.
  2274. :return: None
  2275. """
  2276. for act in self.ui.menutool.actions():
  2277. self.ui.menutool.removeAction(act)
  2278. def init_tools(self):
  2279. """
  2280. Initialize the Tool tab in the notebook side of the central widget.
  2281. Remove the actions in the Tools menu.
  2282. Instantiate again the FlatCAM tools (plugins).
  2283. All this is required when changing the layout: standard, compact etc.
  2284. :return: None
  2285. """
  2286. log.debug("init_tools()")
  2287. # delete the data currently in the Tools Tab and the Tab itself
  2288. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2289. if widget is not None:
  2290. widget.deleteLater()
  2291. self.ui.notebook.removeTab(2)
  2292. # rebuild the Tools Tab
  2293. self.ui.tool_tab = QtWidgets.QWidget()
  2294. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2295. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2296. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2297. self.ui.tool_scroll_area = VerticalScrollArea()
  2298. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2299. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2300. # first remove all of them
  2301. self.remove_tools()
  2302. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2303. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2304. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2305. # third install all of them
  2306. self.install_tools()
  2307. self.log.debug("Tools are initialized.")
  2308. # def parse_system_fonts(self):
  2309. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2310. # 'params': []})
  2311. def connect_toolbar_signals(self):
  2312. """
  2313. Reconnect the signals to the actions in the toolbar.
  2314. This has to be done each time after the FlatCAM tools are removed/installed.
  2315. :return: None
  2316. """
  2317. # Toolbar
  2318. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2319. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2320. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2321. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2322. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2323. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2324. self.ui.replot_btn.triggered.connect(self.plot_all)
  2325. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2326. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2327. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2328. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2329. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2330. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2331. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2332. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2333. self.ui.delete_btn.triggered.connect(self.on_delete)
  2334. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2335. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2336. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2337. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2338. # Tools Toolbar Signals
  2339. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2340. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2341. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2342. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2343. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2344. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2345. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2346. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2347. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2348. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2349. def object2editor(self):
  2350. """
  2351. Send the current Geometry or Excellon object (if any) into the it's editor.
  2352. :return: None
  2353. """
  2354. self.report_usage("object2editor()")
  2355. edited_object = self.collection.get_active()
  2356. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2357. isinstance(edited_object, FlatCAMExcellon):
  2358. pass
  2359. else:
  2360. self.inform.emit('[WARNING_NOTCL] %s' %
  2361. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2362. return
  2363. if isinstance(edited_object, FlatCAMGeometry):
  2364. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2365. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2366. # we set the notebook to hidden
  2367. self.ui.splitter.setSizes([0, 1])
  2368. if edited_object.multigeo is True:
  2369. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2370. if len(edited_tools) > 1:
  2371. self.inform.emit('[WARNING_NOTCL] %s' %
  2372. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2373. "is not possible.\n"
  2374. "Edit only one geometry at a time."))
  2375. # determine the tool dia of the selected tool
  2376. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2377. # now find the key in the edited_object.tools that has this tooldia
  2378. multi_tool = 1
  2379. for tool in edited_object.tools:
  2380. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2381. multi_tool = tool
  2382. break
  2383. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2384. else:
  2385. self.geo_editor.edit_fcgeometry(edited_object)
  2386. # set call source to the Editor we go into
  2387. self.call_source = 'geo_editor'
  2388. elif isinstance(edited_object, FlatCAMExcellon):
  2389. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2390. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2391. if self.ui.splitter.sizes()[0] == 0:
  2392. self.ui.splitter.setSizes([1, 1])
  2393. self.exc_editor.edit_fcexcellon(edited_object)
  2394. # set call source to the Editor we go into
  2395. self.call_source = 'exc_editor'
  2396. elif isinstance(edited_object, FlatCAMGerber):
  2397. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2398. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2399. if self.ui.splitter.sizes()[0] == 0:
  2400. self.ui.splitter.setSizes([1, 1])
  2401. self.grb_editor.edit_fcgerber(edited_object)
  2402. # set call source to the Editor we go into
  2403. self.call_source = 'grb_editor'
  2404. # make sure that we can't select another object while in Editor Mode:
  2405. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2406. self.ui.project_frame.setDisabled(True)
  2407. # delete any selection shape that might be active as they are not relevant in Editor
  2408. self.delete_selection_shape()
  2409. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2410. self.ui.plot_tab_area.protectTab(0)
  2411. self.inform.emit('[WARNING_NOTCL] %s' %
  2412. _("Editor is activated ..."))
  2413. self.should_we_save = True
  2414. def editor2object(self, cleanup=None):
  2415. """
  2416. Transfers the Geometry or Excellon from it's editor to the current object.
  2417. :return: None
  2418. """
  2419. self.report_usage("editor2object()")
  2420. # do not update a geometry or excellon object unless it comes out of an editor
  2421. if self.call_source != 'app':
  2422. edited_obj = self.collection.get_active()
  2423. if cleanup is None:
  2424. msgbox = QtWidgets.QMessageBox()
  2425. msgbox.setText(_("Do you want to save the edited object?"))
  2426. msgbox.setWindowTitle(_("Close Editor"))
  2427. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2428. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2429. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2430. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2431. msgbox.setDefaultButton(bt_yes)
  2432. msgbox.exec_()
  2433. response = msgbox.clickedButton()
  2434. if response == bt_yes:
  2435. # clean the Tools Tab
  2436. self.ui.tool_scroll_area.takeWidget()
  2437. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2438. self.ui.notebook.setTabText(2, "Tool")
  2439. if isinstance(edited_obj, FlatCAMGeometry):
  2440. obj_type = "Geometry"
  2441. if cleanup is None:
  2442. self.geo_editor.update_fcgeometry(edited_obj)
  2443. self.geo_editor.update_options(edited_obj)
  2444. self.geo_editor.deactivate()
  2445. # update the geo object options so it is including the bounding box values
  2446. try:
  2447. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2448. edited_obj.options['xmin'] = xmin
  2449. edited_obj.options['ymin'] = ymin
  2450. edited_obj.options['xmax'] = xmax
  2451. edited_obj.options['ymax'] = ymax
  2452. except AttributeError as e:
  2453. self.inform.emit('[WARNING] %s' %
  2454. _("Object empty after edit."))
  2455. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2456. elif isinstance(edited_obj, FlatCAMGerber):
  2457. obj_type = "Gerber"
  2458. if cleanup is None:
  2459. self.grb_editor.update_fcgerber()
  2460. self.grb_editor.update_options(edited_obj)
  2461. self.grb_editor.deactivate_grb_editor()
  2462. # delete the old object (the source object) if it was an empty one
  2463. if len(edited_obj.solid_geometry) == 0:
  2464. old_name = edited_obj.options['name']
  2465. self.collection.set_active(old_name)
  2466. self.collection.delete_active()
  2467. elif isinstance(edited_obj, FlatCAMExcellon):
  2468. obj_type = "Excellon"
  2469. if cleanup is None:
  2470. self.exc_editor.update_fcexcellon(edited_obj)
  2471. self.exc_editor.update_options(edited_obj)
  2472. self.exc_editor.deactivate()
  2473. else:
  2474. self.inform.emit('[WARNING_NOTCL] %s' %
  2475. _("Select a Gerber, Geometry or Excellon Object to update."))
  2476. return
  2477. self.inform.emit('[selected] %s %s' %
  2478. (obj_type, _("is updated, returning to App...")))
  2479. elif response == bt_no:
  2480. # clean the Tools Tab
  2481. self.ui.tool_scroll_area.takeWidget()
  2482. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2483. self.ui.notebook.setTabText(2, "Tool")
  2484. if isinstance(edited_obj, FlatCAMGeometry):
  2485. self.geo_editor.deactivate()
  2486. elif isinstance(edited_obj, FlatCAMGerber):
  2487. self.grb_editor.deactivate_grb_editor()
  2488. elif isinstance(edited_obj, FlatCAMExcellon):
  2489. self.exc_editor.deactivate()
  2490. # set focus on the project tab
  2491. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2492. else:
  2493. self.inform.emit('[WARNING_NOTCL] %s' %
  2494. _("Select a Gerber, Geometry or Excellon Object to update."))
  2495. return
  2496. elif response == bt_cancel:
  2497. return
  2498. else:
  2499. if isinstance(edited_obj, FlatCAMGeometry):
  2500. self.geo_editor.deactivate()
  2501. elif isinstance(edited_obj, FlatCAMGerber):
  2502. self.grb_editor.deactivate_grb_editor()
  2503. elif isinstance(edited_obj, FlatCAMExcellon):
  2504. self.exc_editor.deactivate()
  2505. else:
  2506. self.inform.emit('[WARNING_NOTCL] %s' %
  2507. _("Select a Gerber, Geometry or Excellon Object to update."))
  2508. return
  2509. # if notebook is hidden we show it
  2510. if self.ui.splitter.sizes()[0] == 0:
  2511. self.ui.splitter.setSizes([1, 1])
  2512. # restore the call_source to app
  2513. self.call_source = 'app'
  2514. edited_obj.plot()
  2515. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2516. self.ui.plot_tab_area.protectTab(0)
  2517. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2518. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2519. self.ui.project_frame.setDisabled(False)
  2520. def get_last_folder(self):
  2521. """
  2522. Get the folder path from where the last file was opened.
  2523. :return: String, last opened folder path
  2524. """
  2525. return self.defaults["global_last_folder"]
  2526. def get_last_save_folder(self):
  2527. """
  2528. Get the folder path from where the last file was saved.
  2529. :return: String, last saved folder path
  2530. """
  2531. loc = self.defaults["global_last_save_folder"]
  2532. if loc is None:
  2533. loc = self.defaults["global_last_folder"]
  2534. if loc is None:
  2535. loc = os.path.dirname(__file__)
  2536. return loc
  2537. def report_usage(self, resource):
  2538. """
  2539. Increments usage counter for the given resource
  2540. in self.defaults['global_stats'].
  2541. :param resource: Name of the resource.
  2542. :return: None
  2543. """
  2544. if resource in self.defaults['global_stats']:
  2545. self.defaults['global_stats'][resource] += 1
  2546. else:
  2547. self.defaults['global_stats'][resource] = 1
  2548. def init_tcl(self):
  2549. """
  2550. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2551. :return: None
  2552. """
  2553. if hasattr(self, 'tcl'):
  2554. # self.tcl = None
  2555. # TODO we need to clean non default variables and procedures here
  2556. # new object cannot be used here as it will not remember values created for next passes,
  2557. # because tcl was execudted in old instance of TCL
  2558. pass
  2559. else:
  2560. self.tcl = tk.Tcl()
  2561. self.setup_shell()
  2562. self.log.debug("TCL Shell has been initialized.")
  2563. # TODO: This shouldn't be here.
  2564. class TclErrorException(Exception):
  2565. """
  2566. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2567. """
  2568. pass
  2569. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2570. """
  2571. Shows a message on the FlatCAM Shell
  2572. :param msg: Message to display.
  2573. :param show: Opens the shell.
  2574. :param error: Shows the message as an error.
  2575. :param warning: Shows the message as an warning.
  2576. :param success: Shows the message as an success.
  2577. :param selected: Indicate that something was selected on canvas
  2578. :return: None
  2579. """
  2580. if show:
  2581. self.ui.shell_dock.show()
  2582. try:
  2583. if error:
  2584. self.shell.append_error(msg + "\n")
  2585. elif warning:
  2586. self.shell.append_warning(msg + "\n")
  2587. elif success:
  2588. self.shell.append_success(msg + "\n")
  2589. elif selected:
  2590. self.shell.append_selected(msg + "\n")
  2591. else:
  2592. self.shell.append_output(msg + "\n")
  2593. except AttributeError:
  2594. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2595. def raise_tcl_unknown_error(self, unknownException):
  2596. """
  2597. Raise exception if is different type than TclErrorException
  2598. this is here mainly to show unknown errors inside TCL shell console.
  2599. :param unknownException:
  2600. :return:
  2601. """
  2602. if not isinstance(unknownException, self.TclErrorException):
  2603. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2604. else:
  2605. raise unknownException
  2606. def display_tcl_error(self, error, error_info=None):
  2607. """
  2608. Escape bracket [ with '\' otherwise there is error
  2609. "ERROR: missing close-bracket" instead of real error
  2610. :param error: it may be text or exception
  2611. :param error_info: Some informations about the error
  2612. :return: None
  2613. """
  2614. if isinstance(error, Exception):
  2615. exc_type, exc_value, exc_traceback = error_info
  2616. if not isinstance(error, self.TclErrorException):
  2617. show_trace = 1
  2618. else:
  2619. show_trace = int(self.defaults['global_verbose_error_level'])
  2620. if show_trace > 0:
  2621. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2622. trc_formated = []
  2623. for a in reversed(trc):
  2624. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2625. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2626. else:
  2627. text = "%s" % error
  2628. else:
  2629. text = error
  2630. text = text.replace('[', '\\[').replace('"', '\\"')
  2631. self.tcl.eval('return -code error "%s"' % text)
  2632. def raise_tcl_error(self, text):
  2633. """
  2634. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2635. :param text: text of error
  2636. :return: raise exception
  2637. """
  2638. self.display_tcl_error(text)
  2639. raise self.TclErrorException(text)
  2640. def exec_command(self, text, no_plot=None):
  2641. """
  2642. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2643. Also handles execution in separated threads
  2644. :param text: FlatCAM TclCommand with parameters
  2645. :return: output if there was any
  2646. """
  2647. self.report_usage('exec_command')
  2648. result = self.exec_command_test(text, False)
  2649. # MS: added this method call so the geometry is updated once the TCL command is executed
  2650. # if no_plot is None:
  2651. # self.plot_all()
  2652. return result
  2653. def exec_command_test(self, text, reraise=True):
  2654. """
  2655. Same as exec_command(...) with additional control over exceptions.
  2656. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2657. :param text: Input command
  2658. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2659. :return: Output from the command
  2660. """
  2661. tcl_command_string = str(text)
  2662. try:
  2663. self.shell.open_proccessing() # Disables input box.
  2664. result = self.tcl.eval(str(tcl_command_string))
  2665. if result != 'None':
  2666. self.shell.append_output(result + '\n')
  2667. except tk.TclError as e:
  2668. # This will display more precise answer if something in TCL shell fails
  2669. result = self.tcl.eval("set errorInfo")
  2670. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2671. self.shell.append_error('ERROR: ' + result + '\n')
  2672. # Show error in console and just return or in test raise exception
  2673. if reraise:
  2674. raise e
  2675. finally:
  2676. self.shell.close_proccessing()
  2677. pass
  2678. return result
  2679. # """
  2680. # Code below is unsused. Saved for later.
  2681. # """
  2682. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2683. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2684. # self.log.debug(parts)
  2685. # try:
  2686. # if parts[0] not in commands:
  2687. # self.shell.append_error("Unknown command\n")
  2688. # return
  2689. #
  2690. # #import inspect
  2691. # #inspect.getargspec(someMethod)
  2692. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2693. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2694. # self.shell.append_error(
  2695. # "Command %s takes %d arguments. %d given.\n" %
  2696. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2697. # )
  2698. # return
  2699. #
  2700. # cmdfcn = commands[parts[0]]["fcn"]
  2701. # cmdconv = commands[parts[0]]["converters"]
  2702. # if len(parts) - 1 > 0:
  2703. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2704. # else:
  2705. # retval = cmdfcn()
  2706. # retfcn = commands[parts[0]]["retfcn"]
  2707. # if retval and retfcn(retval):
  2708. # self.shell.append_output(retfcn(retval) + "\n")
  2709. #
  2710. # except Exception as e:
  2711. # #self.shell.append_error(''.join(traceback.format_exc()))
  2712. # #self.shell.append_error("?\n")
  2713. # self.shell.append_error(str(e) + "\n")
  2714. def info(self, msg):
  2715. """
  2716. Informs the user. Normally on the status bar, optionally
  2717. also on the shell.
  2718. :param msg: Text to write.
  2719. :return: None
  2720. """
  2721. # Type of message in brackets at the beginning of the message.
  2722. match = re.search("\[([^\]]+)\](.*)", msg)
  2723. if match:
  2724. level = match.group(1)
  2725. msg_ = match.group(2)
  2726. self.ui.fcinfo.set_status(str(msg_), level=level)
  2727. if level.lower() == "error":
  2728. self.shell_message(msg, error=True, show=True)
  2729. elif level.lower() == "warning":
  2730. self.shell_message(msg, warning=True, show=True)
  2731. elif level.lower() == "error_notcl":
  2732. self.shell_message(msg, error=True, show=False)
  2733. elif level.lower() == "warning_notcl":
  2734. self.shell_message(msg, warning=True, show=False)
  2735. elif level.lower() == "success":
  2736. self.shell_message(msg, success=True, show=False)
  2737. elif level.lower() == "selected":
  2738. self.shell_message(msg, selected=True, show=False)
  2739. else:
  2740. self.shell_message(msg, show=False)
  2741. else:
  2742. self.ui.fcinfo.set_status(str(msg), level="info")
  2743. # make sure that if the message is to clear the infobar with a space
  2744. # is not printed over and over on the shell
  2745. if msg != '':
  2746. self.shell_message(msg)
  2747. def restore_toolbar_view(self):
  2748. """
  2749. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2750. was saved in the defaults dictionary.
  2751. :return: None
  2752. """
  2753. tb = self.defaults["global_toolbar_view"]
  2754. if tb & 1:
  2755. self.ui.toolbarfile.setVisible(True)
  2756. else:
  2757. self.ui.toolbarfile.setVisible(False)
  2758. if tb & 2:
  2759. self.ui.toolbargeo.setVisible(True)
  2760. else:
  2761. self.ui.toolbargeo.setVisible(False)
  2762. if tb & 4:
  2763. self.ui.toolbarview.setVisible(True)
  2764. else:
  2765. self.ui.toolbarview.setVisible(False)
  2766. if tb & 8:
  2767. self.ui.toolbartools.setVisible(True)
  2768. else:
  2769. self.ui.toolbartools.setVisible(False)
  2770. if tb & 16:
  2771. self.ui.exc_edit_toolbar.setVisible(True)
  2772. else:
  2773. self.ui.exc_edit_toolbar.setVisible(False)
  2774. if tb & 32:
  2775. self.ui.geo_edit_toolbar.setVisible(True)
  2776. else:
  2777. self.ui.geo_edit_toolbar.setVisible(False)
  2778. if tb & 64:
  2779. self.ui.grb_edit_toolbar.setVisible(True)
  2780. else:
  2781. self.ui.grb_edit_toolbar.setVisible(False)
  2782. if tb & 128:
  2783. self.ui.snap_toolbar.setVisible(True)
  2784. else:
  2785. self.ui.snap_toolbar.setVisible(False)
  2786. if tb & 256:
  2787. self.ui.toolbarshell.setVisible(True)
  2788. else:
  2789. self.ui.toolbarshell.setVisible(False)
  2790. def load_defaults(self, filename):
  2791. """
  2792. Loads the aplication's default settings from current_defaults.FlatConfig into
  2793. ``self.defaults``.
  2794. :return: None
  2795. """
  2796. try:
  2797. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2798. options = f.read()
  2799. f.close()
  2800. except IOError:
  2801. self.log.error("Could not load defaults file.")
  2802. self.inform.emit('[ERROR] %s' %
  2803. _("Could not load defaults file."))
  2804. # in case the defaults file can't be loaded, show all toolbars
  2805. self.defaults["global_toolbar_view"] = 511
  2806. return
  2807. try:
  2808. defaults = json.loads(options)
  2809. except:
  2810. # in case the defaults file can't be loaded, show all toolbars
  2811. self.defaults["global_toolbar_view"] = 511
  2812. e = sys.exc_info()[0]
  2813. App.log.error(str(e))
  2814. self.inform.emit('[ERROR] %s' %
  2815. _("Failed to parse defaults file."))
  2816. return
  2817. self.defaults.update(defaults)
  2818. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2819. # restore the toolbar view
  2820. self.restore_toolbar_view()
  2821. def on_import_preferences(self):
  2822. """
  2823. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2824. ``self.defaults``.
  2825. :return: None
  2826. """
  2827. self.report_usage("on_import_preferences")
  2828. App.log.debug("on_import_preferences()")
  2829. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2830. try:
  2831. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2832. directory=self.data_path,
  2833. filter=filter_)
  2834. except TypeError:
  2835. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2836. filter=filter_)
  2837. filename = str(filename)
  2838. if filename == "":
  2839. self.inform.emit('[WARNING_NOTCL] %s' %
  2840. _("FlatCAM preferences import cancelled."))
  2841. else:
  2842. try:
  2843. f = open(filename)
  2844. options = f.read()
  2845. f.close()
  2846. except IOError:
  2847. self.log.error("Could not load defaults file.")
  2848. self.inform.emit('[ERROR_NOTCL] %s' %
  2849. _("Could not load defaults file."))
  2850. return
  2851. try:
  2852. defaults_from_file = json.loads(options)
  2853. except Exception as e:
  2854. e = sys.exc_info()[0]
  2855. App.log.error(str(e))
  2856. self.inform.emit('[ERROR_NOTCL] %s' %
  2857. _("Failed to parse defaults file."))
  2858. return
  2859. self.defaults.update(defaults_from_file)
  2860. self.on_preferences_edited()
  2861. self.inform.emit('[success] %s: %s' %
  2862. (_("Imported Defaults from"), filename))
  2863. def on_export_preferences(self):
  2864. """
  2865. Save the defaults dictionary to a file.
  2866. :return: None
  2867. """
  2868. self.report_usage("on_export_preferences")
  2869. App.log.debug("on_export_preferences()")
  2870. defaults_file_content = None
  2871. self.date = str(datetime.today()).rpartition('.')[0]
  2872. self.date = ''.join(c for c in self.date if c not in ':-')
  2873. self.date = self.date.replace(' ', '_')
  2874. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  2875. try:
  2876. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2877. caption=_("Export FlatCAM Preferences"),
  2878. directory=self.data_path + '/preferences_' + self.date,
  2879. filter=filter__
  2880. )
  2881. except TypeError:
  2882. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  2883. filter=filter__)
  2884. filename = str(filename)
  2885. defaults_from_file = {}
  2886. if filename == "":
  2887. self.inform.emit('[WARNING_NOTCL] %s' %
  2888. _("FlatCAM preferences export cancelled."))
  2889. return
  2890. else:
  2891. try:
  2892. f = open(filename, 'w')
  2893. defaults_file_content = f.read()
  2894. f.close()
  2895. except PermissionError:
  2896. self.inform.emit('[WARNING] %s' %
  2897. _("Permission denied, saving not possible.\n"
  2898. "Most likely another app is holding the file open and not accessible."))
  2899. return
  2900. except IOError:
  2901. App.log.debug('Creating a new preferences file ...')
  2902. f = open(filename, 'w')
  2903. json.dump({}, f)
  2904. f.close()
  2905. except:
  2906. e = sys.exc_info()[0]
  2907. App.log.error("Could not load defaults file.")
  2908. App.log.error(str(e))
  2909. self.inform.emit('[ERROR_NOTCL] %s' %
  2910. _("Could not load preferences file."))
  2911. return
  2912. try:
  2913. defaults_from_file = json.loads(defaults_file_content)
  2914. except:
  2915. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2916. # Update options
  2917. self.defaults_read_form()
  2918. defaults_from_file.update(self.defaults)
  2919. self.propagate_defaults(silent=True)
  2920. # Save update options
  2921. try:
  2922. f = open(filename, "w")
  2923. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  2924. f.close()
  2925. except:
  2926. self.inform.emit('[ERROR_NOTCL] %s' %
  2927. _("Failed to write defaults to file."))
  2928. return
  2929. if self.defaults["global_open_style"] is False:
  2930. self.file_opened.emit("preferences", filename)
  2931. self.file_saved.emit("preferences", filename)
  2932. self.inform.emit('[success] %s: %s' %
  2933. (_("Exported preferences to"), filename))
  2934. def on_preferences_open_folder(self):
  2935. """
  2936. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  2937. :return: None
  2938. """
  2939. self.report_usage("on_preferences_open_folder()")
  2940. if sys.platform == 'win32':
  2941. subprocess.Popen('explorer %s' % self.data_path)
  2942. elif sys.platform == 'darwin':
  2943. os.system('open "%s"' % self.data_path)
  2944. else:
  2945. subprocess.Popen(['xdg-open', self.data_path])
  2946. self.inform.emit('[success] %s' %
  2947. _("FlatCAM Preferences Folder opened."))
  2948. def save_geometry(self, x, y, width, height, notebook_width):
  2949. """
  2950. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2951. launch of the application.
  2952. :param x: X position of the main window
  2953. :param y: Y position of the main window
  2954. :param width: width of the main window
  2955. :param height: height of the main window
  2956. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2957. :return: None
  2958. """
  2959. self.defaults["global_def_win_x"] = x
  2960. self.defaults["global_def_win_y"] = y
  2961. self.defaults["global_def_win_w"] = width
  2962. self.defaults["global_def_win_h"] = height
  2963. self.defaults["global_def_notebook_width"] = notebook_width
  2964. self.save_defaults()
  2965. def message_dialog(self, title, message, kind="info"):
  2966. """
  2967. Builds and show a custom QMessageBox to be used in FlatCAM.
  2968. :param title: title of the QMessageBox
  2969. :param message: message to be displayed
  2970. :param kind: type of QMessageBox; will display a specific icon.
  2971. :return:
  2972. """
  2973. icon = {"info": QtWidgets.QMessageBox.Information,
  2974. "warning": QtWidgets.QMessageBox.Warning,
  2975. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2976. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2977. dlg.setText(message)
  2978. dlg.exec_()
  2979. def register_recent(self, kind, filename):
  2980. """
  2981. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2982. dictionary.
  2983. :param kind: type of file that was opened
  2984. :param filename: the path and file name for the file that was opened
  2985. :return:
  2986. """
  2987. self.log.debug("register_recent()")
  2988. self.log.debug(" %s" % kind)
  2989. self.log.debug(" %s" % filename)
  2990. record = {'kind': str(kind), 'filename': str(filename)}
  2991. if record in self.recent:
  2992. return
  2993. if record in self.recent_projects:
  2994. return
  2995. if record['kind'] == 'project':
  2996. self.recent_projects.insert(0, record)
  2997. else:
  2998. self.recent.insert(0, record)
  2999. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3000. self.recent.pop()
  3001. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3002. self.recent_projects.pop()
  3003. try:
  3004. f = open(self.data_path + '/recent.json', 'w')
  3005. except IOError:
  3006. App.log.error("Failed to open recent items file for writing.")
  3007. self.inform.emit('[ERROR_NOTCL] %s' %
  3008. _('Failed to open recent files file for writing.'))
  3009. return
  3010. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3011. f.close()
  3012. try:
  3013. fp = open(self.data_path + '/recent_projects.json', 'w')
  3014. except IOError:
  3015. App.log.error("Failed to open recent items file for writing.")
  3016. self.inform.emit('[ERROR_NOTCL] %s' %
  3017. _('Failed to open recent projects file for writing.'))
  3018. return
  3019. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3020. fp.close()
  3021. # Re-build the recent items menu
  3022. self.setup_recent_items()
  3023. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3024. """
  3025. Creates a new specialized FlatCAMObj and attaches it to the application,
  3026. this is, updates the GUI accordingly, any other records and plots it.
  3027. This method is thread-safe.
  3028. Notes:
  3029. * If the name is in use, the self.collection will modify it
  3030. when appending it to the collection. There is no need to handle
  3031. name conflicts here.
  3032. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3033. :type kind: str
  3034. :param name: Name for the object.
  3035. :type name: str
  3036. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3037. The function is called with 2 parameters: the new object and the App instance.
  3038. :type initialize: function
  3039. :param active:
  3040. :param fit:
  3041. :param plot: If to plot the resulting object
  3042. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3043. self.colleaction
  3044. :return: None
  3045. :rtype: None
  3046. """
  3047. App.log.debug("new_object()")
  3048. obj_plot = plot
  3049. obj_autoselected = autoselected
  3050. t0 = time.time() # Debug
  3051. # ## Create object
  3052. classdict = {
  3053. "gerber": FlatCAMGerber,
  3054. "excellon": FlatCAMExcellon,
  3055. "cncjob": FlatCAMCNCjob,
  3056. "geometry": FlatCAMGeometry
  3057. }
  3058. App.log.debug("Calling object constructor...")
  3059. obj = classdict[kind](name)
  3060. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3061. # Set options from "Project options" form
  3062. self.options_read_form()
  3063. # IMPORTANT
  3064. # The key names in defaults and options dictionary's are not random:
  3065. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3066. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3067. # the options from project options form into the self.options. After that, below, depending on the type of
  3068. # object that is created, it will strip the name of the object and the underline (if the original key was
  3069. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3070. # "toolchange"
  3071. for option in self.options:
  3072. if option.find(kind + "_") == 0:
  3073. oname = option[len(kind) + 1:]
  3074. obj.options[oname] = self.options[option]
  3075. obj.isHovering = False
  3076. obj.notHovering = True
  3077. # Initialize as per user request
  3078. # User must take care to implement initialize
  3079. # in a thread-safe way as is is likely that we
  3080. # have been invoked in a separate thread.
  3081. t1 = time.time()
  3082. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3083. try:
  3084. return_value = initialize(obj, self)
  3085. except Exception as e:
  3086. msg = '[ERROR_NOTCL] %s' % \
  3087. _("An internal error has ocurred. See shell.\n")
  3088. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3089. msg += traceback.format_exc()
  3090. self.inform.emit(msg)
  3091. # if str(e) == "Empty Geometry":
  3092. # self.inform.emit("[ERROR_NOTCL] )
  3093. # else:
  3094. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3095. return "fail"
  3096. t2 = time.time()
  3097. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3098. if return_value == 'fail':
  3099. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3100. return "fail"
  3101. # Check units and convert if necessary
  3102. # This condition CAN be true because initialize() can change obj.units
  3103. if self.options["units"].upper() != obj.units.upper():
  3104. self.inform.emit('%s: %s' %
  3105. (_("Converting units to "), self.options["units"]))
  3106. obj.convert_units(self.options["units"])
  3107. t3 = time.time()
  3108. self.log.debug("%f seconds converting units." % (t3 - t2))
  3109. # Create the bounding box for the object and then add the results to the obj.options
  3110. try:
  3111. xmin, ymin, xmax, ymax = obj.bounds()
  3112. obj.options['xmin'] = xmin
  3113. obj.options['ymin'] = ymin
  3114. obj.options['xmax'] = xmax
  3115. obj.options['ymax'] = ymax
  3116. except Exception as e:
  3117. log.warning("The object has no bounds properties. %s" % str(e))
  3118. return "fail"
  3119. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3120. # Move the object to the main thread and let the app know that it is available.
  3121. obj.moveToThread(self.main_thread)
  3122. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3123. return obj
  3124. def new_excellon_object(self):
  3125. """
  3126. Creates a new, blank Excellon object.
  3127. :return: None
  3128. """
  3129. self.report_usage("new_excellon_object()")
  3130. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3131. def new_geometry_object(self):
  3132. """
  3133. Creates a new, blank and single-tool Geometry object.
  3134. :return: None
  3135. """
  3136. self.report_usage("new_geometry_object()")
  3137. def initialize(obj, self):
  3138. obj.multitool = False
  3139. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3140. def new_gerber_object(self):
  3141. """
  3142. Creates a new, blank Gerber object.
  3143. :return: None
  3144. """
  3145. self.report_usage("new_gerber_object()")
  3146. def initialize(grb_obj, self):
  3147. grb_obj.multitool = False
  3148. grb_obj.source_file = []
  3149. grb_obj.multigeo = False
  3150. grb_obj.follow = False
  3151. grb_obj.apertures = {}
  3152. grb_obj.solid_geometry = []
  3153. try:
  3154. grb_obj.options['xmin'] = 0
  3155. grb_obj.options['ymin'] = 0
  3156. grb_obj.options['xmax'] = 0
  3157. grb_obj.options['ymax'] = 0
  3158. except KeyError:
  3159. pass
  3160. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3161. def on_object_created(self, obj, plot, autoselect):
  3162. """
  3163. Event callback for object creation.
  3164. It will add the new object to the collection. After that it will plot the object in a threaded way
  3165. :param obj: The newly created FlatCAM object.
  3166. :param plot: if the newly create object t obe plotted
  3167. :param autoselect: if the newly created object to be autoselected after creation
  3168. :return: None
  3169. """
  3170. t0 = time.time() # DEBUG
  3171. self.log.debug("on_object_created()")
  3172. # The Collection might change the name if there is a collision
  3173. self.collection.append(obj)
  3174. # after adding the object to the collection always update the list of objects that are in the collection
  3175. self.all_objects_list = self.collection.get_list()
  3176. # self.inform.emit('[selected] %s created & selected: %s' %
  3177. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3178. if obj.kind == 'gerber':
  3179. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3180. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3181. elif obj.kind == 'excellon':
  3182. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3183. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3184. elif obj.kind == 'cncjob':
  3185. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3186. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3187. elif obj.kind == 'geometry':
  3188. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3189. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3190. # update the SHELL auto-completer model with the name of the new object
  3191. self.myKeywords.append(obj.options['name'])
  3192. self.shell._edit.set_model_data(self.myKeywords)
  3193. self.ui.code_editor.set_model_data(self.myKeywords)
  3194. if autoselect:
  3195. # select the just opened object but deselect the previous ones
  3196. self.collection.set_all_inactive()
  3197. self.collection.set_active(obj.options["name"])
  3198. else:
  3199. self.collection.set_all_inactive()
  3200. # here it is done the object plotting
  3201. def worker_task(t_obj):
  3202. with self.proc_container.new(_("Plotting")):
  3203. if isinstance(t_obj, FlatCAMCNCjob):
  3204. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3205. else:
  3206. t_obj.plot()
  3207. t1 = time.time() # DEBUG
  3208. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3209. self.object_plotted.emit(t_obj)
  3210. # Send to worker
  3211. # self.worker.add_task(worker_task, [self])
  3212. if plot is True:
  3213. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3214. def on_object_changed(self, obj):
  3215. """
  3216. Called whenever the geometry of the object was changed in some way.
  3217. This require the update of it's bounding values so it can be the selected on canvas.
  3218. Update the bounding box data from obj.options
  3219. :param obj: the object that was changed
  3220. :return: None
  3221. """
  3222. xmin, ymin, xmax, ymax = obj.bounds()
  3223. obj.options['xmin'] = xmin
  3224. obj.options['ymin'] = ymin
  3225. obj.options['xmax'] = xmax
  3226. obj.options['ymax'] = ymax
  3227. log.debug("Object changed, updating the bounding box data on self.options")
  3228. # delete the old selection shape
  3229. self.delete_selection_shape()
  3230. self.should_we_save = True
  3231. def on_object_plotted(self, obj):
  3232. """
  3233. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3234. :param obj: object to be fit into view
  3235. :return: None
  3236. """
  3237. self.on_zoom_fit(None)
  3238. def options_read_form(self):
  3239. """
  3240. Same as it's equivalent from the defaults.
  3241. self.options use to store the preferences per project. No longer used.
  3242. :return: None
  3243. """
  3244. for option in self.options_form_fields:
  3245. self.options[option] = self.options_form_fields[option].get_value()
  3246. def options_write_form(self):
  3247. """
  3248. Same as it's equivalent from the defaults.
  3249. self.options use to store the preferences per project. No longer used.
  3250. :return: None
  3251. """
  3252. for option in self.options:
  3253. self.options_write_form_field(option)
  3254. def options_write_form_field(self, field):
  3255. """
  3256. Same as it's equivalent from the defaults.
  3257. self.options use to store the preferences per project. No longer used.
  3258. :return: None
  3259. """
  3260. try:
  3261. self.options_form_fields[field].set_value(self.options[field])
  3262. except KeyError:
  3263. # Changed from error to debug. This allows to have data stored
  3264. # which is not user-editable.
  3265. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3266. pass
  3267. def on_about(self):
  3268. """
  3269. Displays the "about" dialog found in the Menu --> Help.
  3270. :return: None
  3271. """
  3272. self.report_usage("on_about")
  3273. version = self.version
  3274. version_date = self.version_date
  3275. beta = self.beta
  3276. class AboutDialog(QtWidgets.QDialog):
  3277. def __init__(self, parent=None):
  3278. QtWidgets.QDialog.__init__(self, parent)
  3279. # Icon and title
  3280. self.setWindowIcon(parent.app_icon)
  3281. self.setWindowTitle(_("About FlatCAM"))
  3282. self.resize(600, 200)
  3283. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3284. # self.setStyleSheet(
  3285. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3286. # "background-attachment: fixed"
  3287. # )
  3288. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3289. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3290. # palette = QtGui.QPalette()
  3291. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3292. # self.setPalette(palette)
  3293. logo = QtWidgets.QLabel()
  3294. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3295. title = QtWidgets.QLabel(
  3296. "<font size=8><B>FlatCAM</B></font><BR>"
  3297. "{title}<BR>"
  3298. "<BR>"
  3299. "<BR>"
  3300. # "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3301. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3302. # "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3303. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3304. # "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3305. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\"><B>{issue}</B></a><BR>".
  3306. format(title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3307. devel=_("Development"), down=_("DOWNLOAD"), issue=_("Issue tracker"))
  3308. )
  3309. title.setOpenExternalLinks(True)
  3310. closebtn = QtWidgets.QPushButton(_("Close"))
  3311. tab_widget = QtWidgets.QTabWidget()
  3312. description_label = QtWidgets.QLabel(
  3313. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3314. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3315. version=version,beta=('BETA' if beta else ''),
  3316. date=version_date,
  3317. arch=platform.architecture()[0])
  3318. )
  3319. description_label.setOpenExternalLinks(True)
  3320. license_label = QtWidgets.QLabel(
  3321. _(
  3322. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3323. 'Licensed under the MIT license:\n'
  3324. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3325. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3326. 'of this software and associated documentation files (the "Software"), to deal\n'
  3327. 'in the Software without restriction, including without limitation the rights\n'
  3328. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3329. 'copies of the Software, and to permit persons to whom the Software is\n'
  3330. ' furnished to do so, subject to the following conditions:\n\n'
  3331. 'The above copyright notice and this permission notice shall be included in\n'
  3332. 'all copies or substantial portions of the Software.\n\n'
  3333. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3334. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3335. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3336. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3337. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3338. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3339. 'THE SOFTWARE.'
  3340. )
  3341. )
  3342. license_label.setOpenExternalLinks(True)
  3343. # layouts
  3344. layout1 = QtWidgets.QVBoxLayout()
  3345. layout1_1 = QtWidgets.QHBoxLayout()
  3346. layout1_2 = QtWidgets.QHBoxLayout()
  3347. layout2 = QtWidgets.QHBoxLayout()
  3348. layout3 = QtWidgets.QHBoxLayout()
  3349. self.setLayout(layout1)
  3350. layout1.addLayout(layout1_1)
  3351. layout1.addLayout(layout1_2)
  3352. layout1.addLayout(layout2)
  3353. layout1.addLayout(layout3)
  3354. layout1_1.addStretch()
  3355. layout1_1.addWidget(description_label)
  3356. layout1_2.addWidget(tab_widget)
  3357. self.splash_tab = QtWidgets.QWidget()
  3358. self.splash_tab.setObjectName("splash_about")
  3359. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3360. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3361. tab_widget.addTab(self.splash_tab, _("Splash"))
  3362. self.programmmers_tab = QtWidgets.QWidget()
  3363. self.programmmers_tab.setObjectName("programmers_about")
  3364. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3365. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3366. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3367. self.translators_tab = QtWidgets.QWidget()
  3368. self.translators_tab.setObjectName("translators_about")
  3369. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3370. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3371. tab_widget.addTab(self.translators_tab, _("Translators"))
  3372. self.license_tab = QtWidgets.QWidget()
  3373. self.license_tab.setObjectName("license_about")
  3374. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3375. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3376. tab_widget.addTab(self.license_tab, _("License"))
  3377. self.splash_tab_layout.addWidget(logo, stretch=0)
  3378. self.splash_tab_layout.addWidget(title, stretch=1)
  3379. self.prog_grid_lay = QtWidgets.QGridLayout()
  3380. prog_widget = QtWidgets.QWidget()
  3381. prog_widget.setLayout(self.prog_grid_lay)
  3382. self.programmmers_tab_layout.addWidget(prog_widget)
  3383. self.programmmers_tab_layout.addStretch()
  3384. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3385. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3386. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3387. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  3388. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3389. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 1)
  3390. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3391. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  3392. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3393. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Maintainer >=2019")), 4, 1)
  3394. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 5, 0)
  3395. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 1)
  3396. self.translator_grid_lay = QtWidgets.QGridLayout()
  3397. trans_widget = QtWidgets.QWidget()
  3398. trans_widget.setLayout(self.translator_grid_lay)
  3399. self.translators_tab_layout.addWidget(trans_widget)
  3400. self.translators_tab_layout.addStretch()
  3401. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3402. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3403. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3404. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3405. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3406. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3407. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 2, 0)
  3408. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3409. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3410. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 3, 0)
  3411. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3412. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3413. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 4, 0)
  3414. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 4, 1)
  3415. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 4, 2)
  3416. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 5, 0)
  3417. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 5, 1)
  3418. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 2)
  3419. self.translator_grid_lay.setColumnStretch(0, 0)
  3420. # self.translators_tab_layout.addStretch()
  3421. self.license_tab_layout.addWidget(license_label)
  3422. self.license_tab_layout.addStretch()
  3423. layout3.addStretch()
  3424. layout3.addWidget(closebtn)
  3425. closebtn.clicked.connect(self.accept)
  3426. AboutDialog(self.ui).exec_()
  3427. def on_file_savedefaults(self):
  3428. """
  3429. Callback for menu item File->Save Defaults. Saves application default options
  3430. ``self.defaults`` to current_defaults.FlatConfig.
  3431. :return: None
  3432. """
  3433. self.save_defaults()
  3434. # def on_app_exit(self):
  3435. # self.report_usage("on_app_exit()")
  3436. #
  3437. # if self.collection.get_list():
  3438. # msgbox = QtWidgets.QMessageBox()
  3439. # # msgbox.setText("<B>Save changes ...</B>")
  3440. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3441. # "\n"
  3442. # "Do you want to Save the project?")
  3443. # msgbox.setWindowTitle("Save changes")
  3444. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3445. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3446. # QtWidgets.QMessageBox.Cancel)
  3447. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3448. #
  3449. # response = msgbox.exec_()
  3450. #
  3451. # if response == QtWidgets.QMessageBox.Yes:
  3452. # self.on_file_saveprojectas(thread=False)
  3453. # elif response == QtWidgets.QMessageBox.Cancel:
  3454. # return
  3455. # self.save_defaults()
  3456. # else:
  3457. # self.save_defaults()
  3458. # log.debug("Application defaults saved ... Exit event.")
  3459. # QtWidgets.qApp.quit()
  3460. def save_defaults(self, silent=False, data_path=None):
  3461. """
  3462. Saves application default options
  3463. ``self.defaults`` to current_defaults.FlatConfig file.
  3464. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3465. used at the next launch of the application.
  3466. :param silent: whether to display a message in status bar or not; boolean
  3467. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3468. When the application is portable it should be a mobile location.
  3469. :return: None
  3470. """
  3471. self.report_usage("save_defaults")
  3472. if data_path is None:
  3473. data_path = self.data_path
  3474. # Read options from file
  3475. try:
  3476. f = open(data_path + "/current_defaults.FlatConfig")
  3477. defaults_file_content = f.read()
  3478. f.close()
  3479. except:
  3480. e = sys.exc_info()[0]
  3481. App.log.error("Could not load defaults file.")
  3482. App.log.error(str(e))
  3483. self.inform.emit('[ERROR_NOTCL] %s' %
  3484. _("Could not load defaults file."))
  3485. return
  3486. try:
  3487. defaults = json.loads(defaults_file_content)
  3488. except:
  3489. e = sys.exc_info()[0]
  3490. App.log.error("Failed to parse defaults file.")
  3491. App.log.error(str(e))
  3492. self.inform.emit('[ERROR_NOTCL] %s' %
  3493. _("Failed to parse defaults file."))
  3494. return
  3495. # Update options
  3496. self.defaults_read_form()
  3497. defaults.update(self.defaults)
  3498. self.propagate_defaults(silent=True)
  3499. # Save the toolbar view
  3500. tb_status = 0
  3501. if self.ui.toolbarfile.isVisible():
  3502. tb_status += 1
  3503. if self.ui.toolbargeo.isVisible():
  3504. tb_status += 2
  3505. if self.ui.toolbarview.isVisible():
  3506. tb_status += 4
  3507. if self.ui.toolbartools.isVisible():
  3508. tb_status += 8
  3509. if self.ui.exc_edit_toolbar.isVisible():
  3510. tb_status += 16
  3511. if self.ui.geo_edit_toolbar.isVisible():
  3512. tb_status += 32
  3513. if self.ui.grb_edit_toolbar.isVisible():
  3514. tb_status += 64
  3515. if self.ui.snap_toolbar.isVisible():
  3516. tb_status += 128
  3517. if self.ui.toolbarshell.isVisible():
  3518. tb_status += 256
  3519. self.defaults["global_toolbar_view"] = tb_status
  3520. # Save update options
  3521. try:
  3522. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3523. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3524. f.close()
  3525. except:
  3526. self.inform.emit('[ERROR_NOTCL] %s' %
  3527. _("Failed to write defaults to file."))
  3528. return
  3529. if not silent:
  3530. self.inform.emit('[success] %s' %
  3531. _("Preferences saved."))
  3532. def save_factory_defaults(self, silent=False, data_path=None):
  3533. """
  3534. Saves application factory default options
  3535. ``self.defaults`` to factory_defaults.FlatConfig.
  3536. It's a one time job done just after the first install.
  3537. :param silent: whether to display a message in status bar or not; boolean
  3538. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3539. When the application is portable it should be a mobile location.
  3540. :return: None
  3541. """
  3542. self.report_usage("save_factory_defaults")
  3543. if data_path is None:
  3544. data_path = self.data_path
  3545. # Read options from file
  3546. try:
  3547. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3548. factory_defaults_file_content = f_f_def.read()
  3549. f_f_def.close()
  3550. except:
  3551. e = sys.exc_info()[0]
  3552. App.log.error("Could not load factory defaults file.")
  3553. App.log.error(str(e))
  3554. self.inform.emit('[ERROR_NOTCL] %s' %
  3555. _("Could not load factory defaults file."))
  3556. return
  3557. try:
  3558. factory_defaults = json.loads(factory_defaults_file_content)
  3559. except:
  3560. e = sys.exc_info()[0]
  3561. App.log.error("Failed to parse factory defaults file.")
  3562. App.log.error(str(e))
  3563. self.inform.emit('[ERROR_NOTCL] %s' %
  3564. _("Failed to parse factory defaults file."))
  3565. return
  3566. # Update options
  3567. self.defaults_read_form()
  3568. factory_defaults.update(self.defaults)
  3569. self.propagate_defaults(silent=True)
  3570. # Save update options
  3571. try:
  3572. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3573. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3574. f_f_def_s.close()
  3575. except:
  3576. self.inform.emit('[ERROR_NOTCL] %s' %
  3577. _("Failed to write factory defaults to file."))
  3578. return
  3579. if silent is False:
  3580. self.inform.emit(_("Factory defaults saved."))
  3581. def final_save(self):
  3582. """
  3583. Callback for doing a preferences save to file whenever the application is about to quit.
  3584. If the project has changes, it will ask the user to save the project.
  3585. :return: None
  3586. """
  3587. if self.save_in_progress:
  3588. self.inform.emit('[WARNING_NOTCL] %s' %
  3589. _("Application is saving the project. Please wait ..."))
  3590. return
  3591. if self.should_we_save and self.collection.get_list():
  3592. msgbox = QtWidgets.QMessageBox()
  3593. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3594. "\n"
  3595. "Do you want to Save the project?"))
  3596. msgbox.setWindowTitle(_("Save changes"))
  3597. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3598. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3599. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3600. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3601. msgbox.setDefaultButton(bt_yes)
  3602. msgbox.exec_()
  3603. response = msgbox.clickedButton()
  3604. if response == bt_yes:
  3605. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3606. elif response == bt_no:
  3607. self.quit_application()
  3608. elif response == bt_cancel:
  3609. return
  3610. else:
  3611. self.quit_application()
  3612. def quit_application(self):
  3613. """
  3614. Called (as a pyslot or not) when the application is quit.
  3615. :return: None
  3616. """
  3617. self.save_defaults()
  3618. log.debug("App.final_save() --> App Defaults saved.")
  3619. # save toolbar state to file
  3620. settings = QSettings("Open Source", "FlatCAM")
  3621. settings.setValue('saved_gui_state', self.ui.saveState())
  3622. settings.setValue('maximized_gui', self.ui.isMaximized())
  3623. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3624. settings.setValue('notebook_font_size',
  3625. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value())
  3626. settings.setValue('axis_font_size',
  3627. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3628. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3629. # This will write the setting to the platform specific storage.
  3630. del settings
  3631. log.debug("App.final_save() --> App UI state saved.")
  3632. QtWidgets.qApp.quit()
  3633. def on_portable_checked(self, state):
  3634. """
  3635. Callback called when the checkbox in Preferences GUI is checked.
  3636. It will set the application as portable by creating the preferences and recent files in the
  3637. 'config' folder found in the FlatCAM installation folder.
  3638. :param state: boolean, the state of the checkbox when clicked/checked
  3639. :return:
  3640. """
  3641. line_no = 0
  3642. data = None
  3643. if sys.platform != 'win32':
  3644. # this won't work in Linux or MacOS
  3645. return
  3646. # test if the app was frozen and choose the path for the configuration file
  3647. if getattr(sys, "frozen", False) is True:
  3648. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3649. else:
  3650. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3651. config_file = current_data_path + '\\configuration.txt'
  3652. try:
  3653. with open(config_file, 'r') as f:
  3654. try:
  3655. data = f.readlines()
  3656. except Exception as e:
  3657. log.debug('App.__init__() -->%s' % str(e))
  3658. return
  3659. except FileNotFoundError:
  3660. pass
  3661. for line in data:
  3662. line = line.strip('\n')
  3663. param = str(line).rpartition('=')
  3664. if param[0] == 'portable':
  3665. break
  3666. line_no += 1
  3667. if state:
  3668. data[line_no] = 'portable=True\n'
  3669. # create the new defauults files
  3670. # create current_defaults.FlatConfig file if there is none
  3671. try:
  3672. f = open(current_data_path + '/current_defaults.FlatConfig')
  3673. f.close()
  3674. except IOError:
  3675. App.log.debug('Creating empty current_defaults.FlatConfig')
  3676. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3677. json.dump({}, f)
  3678. f.close()
  3679. # create factory_defaults.FlatConfig file if there is none
  3680. try:
  3681. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3682. f.close()
  3683. except IOError:
  3684. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3685. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3686. json.dump({}, f)
  3687. f.close()
  3688. try:
  3689. f = open(current_data_path + '/recent.json')
  3690. f.close()
  3691. except IOError:
  3692. App.log.debug('Creating empty recent.json')
  3693. f = open(current_data_path + '/recent.json', 'w')
  3694. json.dump([], f)
  3695. f.close()
  3696. try:
  3697. fp = open(current_data_path + '/recent_projects.json')
  3698. fp.close()
  3699. except IOError:
  3700. App.log.debug('Creating empty recent_projects.json')
  3701. fp = open(current_data_path + '/recent_projects.json', 'w')
  3702. json.dump([], fp)
  3703. fp.close()
  3704. # save the current defaults to the new defaults file
  3705. self.save_defaults(silent=True, data_path=current_data_path)
  3706. self.save_factory_defaults(silent=True, data_path=current_data_path)
  3707. else:
  3708. data[line_no] = 'portable=False\n'
  3709. with open(config_file, 'w') as f:
  3710. f.writelines(data)
  3711. def on_toggle_shell(self):
  3712. """
  3713. Toggle shell: if is visible close it, if it is closed then open it
  3714. :return:
  3715. """
  3716. self.report_usage("on_toggle_shell()")
  3717. if self.ui.shell_dock.isVisible():
  3718. self.ui.shell_dock.hide()
  3719. else:
  3720. self.ui.shell_dock.show()
  3721. def on_register_files(self, obj_type=None):
  3722. """
  3723. Called whenever there is a need to register file extensions with FlatCAM.
  3724. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3725. :param obj_type: the type of object to be register for.
  3726. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3727. :return: None
  3728. """
  3729. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3730. new_reg_path = 'Software\\Classes\\'
  3731. # find if the current user is admin
  3732. try:
  3733. is_admin = os.getuid() == 0
  3734. except AttributeError:
  3735. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3736. if is_admin is True:
  3737. root_path = winreg.HKEY_CLASSES_ROOT
  3738. else:
  3739. root_path = winreg.HKEY_CURRENT_USER
  3740. # create the keys
  3741. def set_reg(name, root_path, new_reg_path, value):
  3742. try:
  3743. winreg.CreateKey(root_path, new_reg_path)
  3744. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3745. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3746. return True
  3747. except WindowsError:
  3748. return False
  3749. # delete key in registry
  3750. def delete_reg(root_path, reg_path, key_to_del):
  3751. key_to_del_path = reg_path + key_to_del
  3752. try:
  3753. winreg.DeleteKey(root_path, key_to_del_path)
  3754. return True
  3755. except WindowsError:
  3756. return False
  3757. if obj_type is None or obj_type == 'excellon':
  3758. exc_list = self.ui.fa_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3759. exc_list = [x for x in exc_list if x != '']
  3760. # register all keys in the Preferences window
  3761. for ext in exc_list:
  3762. new_k = new_reg_path + ext
  3763. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3764. # and unregister those that are no longer in the Preferences windows but are in the file
  3765. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3766. if ext not in exc_list:
  3767. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3768. # now write the updated extensions to the self.defaults
  3769. new_ext = ''
  3770. for ext in exc_list:
  3771. new_ext = new_ext + ext + ', '
  3772. self.defaults["fa_excellon"] = new_ext
  3773. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3774. if obj_type is None or obj_type == 'gcode':
  3775. gco_list = self.ui.fa_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3776. gco_list = [x for x in gco_list if x != '']
  3777. # register all keys in the Preferences window
  3778. for ext in gco_list:
  3779. new_k = new_reg_path + ext
  3780. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3781. # and unregister those that are no longer in the Preferences windows but are in the file
  3782. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3783. if ext not in gco_list:
  3784. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3785. # now write the updated extensions to the self.defaults
  3786. new_ext = ''
  3787. for ext in gco_list:
  3788. new_ext = new_ext + ext + ', '
  3789. self.defaults["fa_gcode"] = new_ext
  3790. self.inform.emit('[success] %s' %
  3791. _("Selected GCode file extensions registered with FlatCAM."))
  3792. if obj_type is None or obj_type == 'gerber':
  3793. grb_list = self.ui.fa_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3794. grb_list = [x for x in grb_list if x != '']
  3795. # register all keys in the Preferences window
  3796. for ext in grb_list:
  3797. new_k = new_reg_path + ext
  3798. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3799. # and unregister those that are no longer in the Preferences windows but are in the file
  3800. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3801. if ext not in grb_list:
  3802. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del=ext)
  3803. # now write the updated extensions to the self.defaults
  3804. new_ext = ''
  3805. for ext in grb_list:
  3806. new_ext = new_ext + ext + ', '
  3807. self.defaults["fa_gerber"] = new_ext
  3808. self.inform.emit('[success] %s' %
  3809. _("Selected Gerber file extensions registered with FlatCAM."))
  3810. def on_edit_join(self, name=None):
  3811. """
  3812. Callback for Edit->Join. Joins the selected geometry objects into
  3813. a new one.
  3814. :return: None
  3815. """
  3816. self.report_usage("on_edit_join()")
  3817. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3818. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3819. tooldias = []
  3820. geo_type_list = set()
  3821. objs = self.collection.get_selected()
  3822. if len(objs) < 2:
  3823. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3824. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3825. return 'fail'
  3826. for obj in objs:
  3827. geo_type_list.add(obj.multigeo)
  3828. # if len(geo_type_list) == 1 means that all list elements are the same
  3829. if len(geo_type_list) != 1:
  3830. self.inform.emit('[ERROR] %s' %
  3831. _("Failed join. The Geometry objects are of different types.\n"
  3832. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3833. "convert from one to another and retry joining \n"
  3834. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3835. "the result may not be what was expected. \n"
  3836. "Check the generated GCODE."))
  3837. return
  3838. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3839. if True in geo_type_list:
  3840. def initialize(obj, app):
  3841. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  3842. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3843. for v in obj.tools.values():
  3844. v['data']['name'] = obj_name_multi
  3845. self.new_object("geometry", obj_name_multi, initialize)
  3846. else:
  3847. def initialize(obj, app):
  3848. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  3849. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3850. for v in obj.tools.values():
  3851. v['data']['name'] = obj_name_single
  3852. self.new_object("geometry", obj_name_single, initialize)
  3853. self.should_we_save = True
  3854. def on_edit_join_exc(self):
  3855. """
  3856. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3857. a new Excellon.
  3858. :return: None
  3859. """
  3860. self.report_usage("on_edit_join_exc()")
  3861. objs = self.collection.get_selected()
  3862. for obj in objs:
  3863. if not isinstance(obj, FlatCAMExcellon):
  3864. self.inform.emit('[ERROR_NOTCL] %s' %
  3865. _("Failed. Excellon joining works only on Excellon objects."))
  3866. return
  3867. if len(objs) < 2:
  3868. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3869. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3870. return 'fail'
  3871. def initialize(obj, app):
  3872. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  3873. self.new_object("excellon", 'Combo_Excellon', initialize)
  3874. self.should_we_save = True
  3875. def on_edit_join_grb(self):
  3876. """
  3877. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3878. a new Gerber object.
  3879. :return: None
  3880. """
  3881. self.report_usage("on_edit_join_grb()")
  3882. objs = self.collection.get_selected()
  3883. for obj in objs:
  3884. if not isinstance(obj, FlatCAMGerber):
  3885. self.inform.emit('[ERROR_NOTCL] %s' %
  3886. _("Failed. Gerber joining works only on Gerber objects."))
  3887. return
  3888. if len(objs) < 2:
  3889. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3890. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3891. return 'fail'
  3892. def initialize(obj, app):
  3893. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  3894. self.new_object("gerber", 'Combo_Gerber', initialize)
  3895. self.should_we_save = True
  3896. def on_convert_singlegeo_to_multigeo(self):
  3897. """
  3898. Called for converting a Geometry object from single-geo to multi-geo.
  3899. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3900. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3901. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3902. the solid-geometry of that tool.
  3903. :return: None
  3904. """
  3905. self.report_usage("on_convert_singlegeo_to_multigeo()")
  3906. obj = self.collection.get_active()
  3907. if obj is None:
  3908. self.inform.emit('[ERROR_NOTCL] %s' %
  3909. _("Failed. Select a Geometry Object and try again."))
  3910. return
  3911. if not isinstance(obj, FlatCAMGeometry):
  3912. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3913. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  3914. return
  3915. obj.multigeo = True
  3916. for tooluid, dict_value in obj.tools.items():
  3917. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3918. if not isinstance(obj.solid_geometry, list):
  3919. obj.solid_geometry = [obj.solid_geometry]
  3920. obj.solid_geometry[:] = []
  3921. obj.plot()
  3922. self.should_we_save = True
  3923. self.inform.emit('[success] %s' %
  3924. _("A Geometry object was converted to MultiGeo type."))
  3925. def on_convert_multigeo_to_singlegeo(self):
  3926. """
  3927. Called for converting a Geometry object from multi-geo to single-geo.
  3928. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3929. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3930. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3931. the solid-geometry of that tool.
  3932. :return: None
  3933. """
  3934. self.report_usage("on_convert_multigeo_to_singlegeo()")
  3935. obj = self.collection.get_active()
  3936. if obj is None:
  3937. self.inform.emit('[ERROR_NOTCL] %s' %
  3938. _("Failed. Select a Geometry Object and try again."))
  3939. return
  3940. if not isinstance(obj, FlatCAMGeometry):
  3941. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3942. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  3943. return
  3944. obj.multigeo = False
  3945. total_solid_geometry = []
  3946. for tooluid, dict_value in obj.tools.items():
  3947. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3948. # clear the original geometry
  3949. dict_value['solid_geometry'][:] = []
  3950. obj.solid_geometry = deepcopy(total_solid_geometry)
  3951. obj.plot()
  3952. self.should_we_save = True
  3953. self.inform.emit('[success] %s' %
  3954. _("A Geometry object was converted to SingleGeo type."))
  3955. def on_options_dict_change(self, field):
  3956. """
  3957. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  3958. current project. This feature is no longer used.
  3959. :param field:
  3960. :return:
  3961. """
  3962. self.options_write_form_field(field)
  3963. if field == "units":
  3964. self.set_screen_units(self.options['units'])
  3965. def on_defaults_dict_change(self, field):
  3966. """
  3967. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3968. Edit -> Preferences tab window.
  3969. :param field: the key of the self.defaults dictionary that was changed.
  3970. :return: None
  3971. """
  3972. self.defaults_write_form_field(field)
  3973. if field == "units":
  3974. self.set_screen_units(self.defaults['units'])
  3975. def set_screen_units(self, units):
  3976. """
  3977. Set the FlatCAM units on the status bar.
  3978. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3979. :return: None
  3980. """
  3981. self.ui.units_label.setText("[" + units.lower() + "]")
  3982. def on_toggle_units(self, no_pref=False):
  3983. """
  3984. Callback for the Units radio-button change in the Preferences tab.
  3985. Changes the application's default units adn for the project too.
  3986. If changing the project's units, the change propagates to all of
  3987. the objects in the project.
  3988. :return: None
  3989. """
  3990. self.report_usage("on_toggle_units")
  3991. if self.toggle_units_ignore:
  3992. return
  3993. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3994. # If option is the same, then ignore
  3995. if new_units == self.defaults["units"].upper():
  3996. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3997. return
  3998. # Options to scale
  3999. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  4000. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4001. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4002. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4003. "excellon_z_pdepth",
  4004. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4005. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4006. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4007. "geometry_feedrate_probe",
  4008. 'cncjob_tooldia',
  4009. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4010. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  4011. "tools_2sided_drilldia", "tools_film_boundary",
  4012. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4013. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4014. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4015. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4016. "tools_transform_offset_y",
  4017. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4018. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4019. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4020. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4021. 'global_gridx', 'global_gridy', 'global_snap_max']
  4022. def scale_options(sfactor):
  4023. for dim in dimensions:
  4024. if dim == 'excellon_toolchangexy':
  4025. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4026. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4027. coords_xy[0] *= sfactor
  4028. coords_xy[1] *= sfactor
  4029. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4030. elif dim == 'geometry_toolchangexy':
  4031. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4032. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4033. coords_xy[0] *= sfactor
  4034. coords_xy[1] *= sfactor
  4035. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4036. elif dim == 'geometry_cnctooldia':
  4037. tools_diameters = []
  4038. try:
  4039. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4040. tools_diameters = [eval(a) for a in tools_string if a != '']
  4041. except Exception as e:
  4042. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4043. self.options['geometry_cnctooldia'] = ''
  4044. for t in range(len(tools_diameters)):
  4045. tools_diameters[t] *= sfactor
  4046. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4047. elif dim == 'tools_ncctools':
  4048. ncctools = []
  4049. try:
  4050. tools_string = self.defaults["tools_ncctools"].split(",")
  4051. ncctools = [eval(a) for a in tools_string if a != '']
  4052. except Exception as e:
  4053. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4054. self.options['tools_ncctools'] = ''
  4055. for t in range(len(ncctools)):
  4056. ncctools[t] *= sfactor
  4057. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4058. elif dim == 'tools_solderpaste_tools':
  4059. sptools = []
  4060. try:
  4061. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4062. sptools = [eval(a) for a in tools_string if a != '']
  4063. except Exception as e:
  4064. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4065. self.options['tools_solderpaste_tools'] = ""
  4066. for t in range(len(sptools)):
  4067. sptools[t] *= sfactor
  4068. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4069. elif dim == 'tools_solderpaste_xy_toolchange':
  4070. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4071. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4072. sp_coords[0] *= sfactor
  4073. sp_coords[1] *= sfactor
  4074. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4075. elif dim == 'global_gridx' or dim == 'global_gridy':
  4076. if new_units == 'IN':
  4077. val = 0.1
  4078. try:
  4079. val = float(self.defaults[dim]) * sfactor
  4080. except Exception as e:
  4081. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4082. self.options[dim] = float('%.6f' % val)
  4083. else:
  4084. val = 0.1
  4085. try:
  4086. val = float(self.defaults[dim]) * sfactor
  4087. except Exception as e:
  4088. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4089. self.options[dim] = float('%.4f' % val)
  4090. else:
  4091. val = 0.1
  4092. try:
  4093. val = float(self.options[dim]) * sfactor
  4094. except Exception as e:
  4095. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4096. self.options[dim] = val
  4097. def scale_defaults(sfactor):
  4098. for dim in dimensions:
  4099. if dim == 'excellon_toolchangexy':
  4100. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4101. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4102. coords_xy[0] *= sfactor
  4103. coords_xy[1] *= sfactor
  4104. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4105. elif dim == 'geometry_toolchangexy':
  4106. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4107. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4108. coords_xy[0] *= sfactor
  4109. coords_xy[1] *= sfactor
  4110. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4111. elif dim == 'geometry_cnctooldia':
  4112. tools_diameters = []
  4113. try:
  4114. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4115. tools_diameters = [eval(a) for a in tools_string if a != '']
  4116. except Exception as e:
  4117. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4118. self.defaults['geometry_cnctooldia'] = ''
  4119. for t in range(len(tools_diameters)):
  4120. tools_diameters[t] *= sfactor
  4121. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4122. elif dim == 'tools_ncctools':
  4123. ncctools = []
  4124. try:
  4125. tools_string = self.defaults["tools_ncctools"].split(",")
  4126. ncctools = [eval(a) for a in tools_string if a != '']
  4127. except Exception as e:
  4128. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4129. self.defaults['tools_ncctools'] = ''
  4130. for t in range(len(ncctools)):
  4131. ncctools[t] *= sfactor
  4132. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4133. elif dim == 'tools_solderpaste_tools':
  4134. sptools = []
  4135. try:
  4136. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4137. sptools = [eval(a) for a in tools_string if a != '']
  4138. except Exception as e:
  4139. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4140. self.defaults['tools_solderpaste_tools'] = ""
  4141. for t in range(len(sptools)):
  4142. sptools[t] *= sfactor
  4143. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4144. elif dim == 'tools_solderpaste_xy_toolchange':
  4145. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4146. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4147. sp_coords[0] *= sfactor
  4148. sp_coords[1] *= sfactor
  4149. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4150. elif dim == 'global_gridx' or dim == 'global_gridy':
  4151. if new_units == 'IN':
  4152. val = 0.1
  4153. try:
  4154. val = float(self.defaults[dim]) * sfactor
  4155. except Exception as e:
  4156. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4157. self.defaults[dim] = float('%.6f' % val)
  4158. else:
  4159. val = 0.1
  4160. try:
  4161. val = float(self.defaults[dim]) * sfactor
  4162. except Exception as e:
  4163. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4164. self.defaults[dim] = float('%.4f' % val)
  4165. else:
  4166. val = 0.1
  4167. try:
  4168. val = float(self.defaults[dim]) * sfactor
  4169. except Exception as e:
  4170. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4171. self.defaults[dim] = val
  4172. # The scaling factor depending on choice of units.
  4173. factor = 1/25.4
  4174. if new_units == 'MM':
  4175. factor = 25.4
  4176. # Changing project units. Warn user.
  4177. msgbox = QtWidgets.QMessageBox()
  4178. msgbox.setWindowTitle(_("Toggle Units"))
  4179. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4180. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4181. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4182. "properties of all objects to be scaled accordingly.\nContinue?"))
  4183. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4184. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4185. msgbox.setDefaultButton(bt_ok)
  4186. msgbox.exec_()
  4187. response = msgbox.clickedButton()
  4188. if response == bt_ok:
  4189. if no_pref is False:
  4190. self.options_read_form()
  4191. scale_options(factor)
  4192. self.options_write_form()
  4193. self.defaults_read_form()
  4194. scale_defaults(factor)
  4195. self.defaults_write_form(fl_units=new_units)
  4196. # save the defaults to file, some may assume that the conversion is enough and it's not
  4197. self.on_save_button()
  4198. self.should_we_save = True
  4199. # change this only if the workspace is active
  4200. if self.defaults['global_workspace'] is True:
  4201. self.plotcanvas.draw_workspace()
  4202. # adjust the grid values on the main toolbar
  4203. dec = 6 if new_units == 'IN'else 4
  4204. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4205. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4206. if not self.ui.grid_gap_link_cb.isChecked():
  4207. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4208. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4209. for obj in self.collection.get_list():
  4210. obj.convert_units(new_units)
  4211. # make that the properties stored in the object are also updated
  4212. self.object_changed.emit(obj)
  4213. obj.build_ui()
  4214. current = self.collection.get_active()
  4215. if current is not None:
  4216. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4217. if not isinstance(current, FlatCAMGeometry):
  4218. current.to_form()
  4219. self.plot_all()
  4220. self.inform.emit('[success] %s: %s' %
  4221. (_("Converted units to"), new_units))
  4222. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4223. self.set_screen_units(new_units)
  4224. else:
  4225. # Undo toggling
  4226. self.toggle_units_ignore = True
  4227. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4228. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4229. else:
  4230. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4231. self.toggle_units_ignore = False
  4232. self.inform.emit('[WARNING_NOTCL]%s' %
  4233. _(" Units conversion cancelled."))
  4234. self.options_read_form()
  4235. self.defaults_read_form()
  4236. def on_toggle_units_click(self):
  4237. try:
  4238. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4239. except (TypeError, AttributeError):
  4240. pass
  4241. if self.defaults["units"] == 'MM':
  4242. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4243. else:
  4244. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4245. self.on_toggle_units(no_pref=True)
  4246. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4247. lambda: self.on_toggle_units(no_pref=False))
  4248. def on_fullscreen(self):
  4249. self.report_usage("on_fullscreen()")
  4250. if self.toggle_fscreen is False:
  4251. if sys.platform == 'win32':
  4252. self.ui.showFullScreen()
  4253. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4254. tb.setVisible(False)
  4255. self.ui.splitter_left.setVisible(False)
  4256. self.toggle_fscreen = True
  4257. else:
  4258. if sys.platform == 'win32':
  4259. self.ui.showNormal()
  4260. self.restore_toolbar_view()
  4261. self.ui.splitter_left.setVisible(True)
  4262. self.toggle_fscreen = False
  4263. def on_toggle_plotarea(self):
  4264. self.report_usage("on_toggle_plotarea()")
  4265. try:
  4266. name = self.ui.plot_tab_area.widget(0).objectName()
  4267. except AttributeError:
  4268. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4269. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4270. self.ui.plot_tab_area.protectTab(0)
  4271. return
  4272. if name != 'plotarea':
  4273. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4274. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4275. self.ui.plot_tab_area.protectTab(0)
  4276. else:
  4277. self.ui.plot_tab_area.closeTab(0)
  4278. def on_toggle_notebook(self):
  4279. if self.ui.splitter.sizes()[0] == 0:
  4280. self.ui.splitter.setSizes([1, 1])
  4281. else:
  4282. self.ui.splitter.setSizes([0, 1])
  4283. def on_toggle_axis(self):
  4284. self.report_usage("on_toggle_axis()")
  4285. if self.toggle_axis is False:
  4286. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4287. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4288. self.plotcanvas.redraw()
  4289. self.toggle_axis = True
  4290. else:
  4291. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4292. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4293. self.plotcanvas.redraw()
  4294. self.toggle_axis = False
  4295. def on_toggle_grid(self):
  4296. self.report_usage("on_toggle_grid()")
  4297. self.ui.grid_snap_btn.trigger()
  4298. def on_options_combo_change(self, sel):
  4299. """
  4300. Called when the combo box to choose between application defaults and
  4301. project option changes value. The corresponding variables are
  4302. copied to the UI.
  4303. :param sel: The option index that was chosen.
  4304. :return: None
  4305. """
  4306. # combo_sel = self.ui.notebook.combo_options.get_active()
  4307. App.log.debug("Options --> %s" % sel)
  4308. # form = [self.defaults_form, self.options_form][sel]
  4309. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4310. if sel == 0:
  4311. self.gen_form = self.ui.general_defaults_form
  4312. self.ger_form = self.ui.gerber_defaults_form
  4313. self.exc_form = self.ui.excellon_defaults_form
  4314. self.geo_form = self.ui.geometry_defaults_form
  4315. self.cnc_form = self.ui.cncjob_defaults_form
  4316. self.tools_form = self.ui.tools_defaults_form
  4317. self.fa_form = self.ui.fa_defaults_form
  4318. elif sel == 1:
  4319. self.gen_form = self.ui.general_options_form
  4320. self.ger_form = self.ui.gerber_options_form
  4321. self.exc_form = self.ui.excellon_options_form
  4322. self.geo_form = self.ui.geometry_options_form
  4323. self.cnc_form = self.ui.cncjob_options_form
  4324. self.tools_form = self.ui.tools_options_form
  4325. self.fa_form = self.ui.fa_options_form
  4326. else:
  4327. return
  4328. try:
  4329. self.ui.general_scroll_area.takeWidget()
  4330. except:
  4331. self.log.debug("Nothing to remove")
  4332. self.ui.general_scroll_area.setWidget(self.gen_form)
  4333. self.gen_form.show()
  4334. try:
  4335. self.ui.gerber_scroll_area.takeWidget()
  4336. except:
  4337. self.log.debug("Nothing to remove")
  4338. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4339. self.ger_form.show()
  4340. try:
  4341. self.ui.excellon_scroll_area.takeWidget()
  4342. except:
  4343. self.log.debug("Nothing to remove")
  4344. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4345. self.exc_form.show()
  4346. try:
  4347. self.ui.geometry_scroll_area.takeWidget()
  4348. except:
  4349. self.log.debug("Nothing to remove")
  4350. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4351. self.geo_form.show()
  4352. try:
  4353. self.ui.cncjob_scroll_area.takeWidget()
  4354. except:
  4355. self.log.debug("Nothing to remove")
  4356. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4357. self.cnc_form.show()
  4358. try:
  4359. self.ui.tools_scroll_area.takeWidget()
  4360. except:
  4361. self.log.debug("Nothing to remove")
  4362. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4363. self.tools_form.show()
  4364. try:
  4365. self.ui.fa_scroll_area.takeWidget()
  4366. except:
  4367. self.log.debug("Nothing to remove")
  4368. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4369. self.fa_form.show()
  4370. self.log.debug("Finished GUI form initialization.")
  4371. # self.options2form()
  4372. def on_excellon_defaults_button(self):
  4373. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4374. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4375. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4376. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4377. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4378. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4379. log.debug("Excellon app defaults loaded ...")
  4380. def on_excellon_options_button(self):
  4381. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4382. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4383. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4384. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4385. self.options_form_fields["excellon_zeros"].set_value('L')
  4386. self.options_form_fields["excellon_units"].set_value('INCH')
  4387. log.debug("Excellon options defaults loaded ...")
  4388. def on_update_exc_export(self, state):
  4389. """
  4390. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  4391. if the update_excellon_cb checkbox is checked
  4392. :param state: state of the checkbox whose signals is tied to his slot
  4393. :return:
  4394. """
  4395. if state:
  4396. # first try to disconnect
  4397. try:
  4398. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.\
  4399. disconnect(self.on_excellon_format_changed)
  4400. except TypeError:
  4401. pass
  4402. try:
  4403. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.\
  4404. disconnect(self.on_excellon_format_changed)
  4405. except TypeError:
  4406. pass
  4407. try:
  4408. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.\
  4409. disconnect(self.on_excellon_format_changed)
  4410. except TypeError:
  4411. pass
  4412. try:
  4413. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.\
  4414. disconnect(self.on_excellon_format_changed)
  4415. except TypeError:
  4416. pass
  4417. try:
  4418. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  4419. disconnect(self.on_excellon_zeros_changed)
  4420. except TypeError:
  4421. pass
  4422. try:
  4423. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  4424. disconnect(self.on_excellon_zeros_changed)
  4425. except TypeError:
  4426. pass
  4427. # the connect them
  4428. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.connect(
  4429. self.on_excellon_format_changed)
  4430. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.connect(
  4431. self.on_excellon_format_changed)
  4432. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.connect(
  4433. self.on_excellon_format_changed)
  4434. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.connect(
  4435. self.on_excellon_format_changed)
  4436. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  4437. self.on_excellon_zeros_changed)
  4438. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  4439. self.on_excellon_units_changed)
  4440. else:
  4441. # disconnect the signals
  4442. try:
  4443. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged. \
  4444. disconnect(self.on_excellon_format_changed)
  4445. except TypeError:
  4446. pass
  4447. try:
  4448. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged. \
  4449. disconnect(self.on_excellon_format_changed)
  4450. except TypeError:
  4451. pass
  4452. try:
  4453. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged. \
  4454. disconnect(self.on_excellon_format_changed)
  4455. except TypeError:
  4456. pass
  4457. try:
  4458. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged. \
  4459. disconnect(self.on_excellon_format_changed)
  4460. except TypeError:
  4461. pass
  4462. try:
  4463. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  4464. disconnect(self.on_excellon_zeros_changed)
  4465. except TypeError:
  4466. pass
  4467. try:
  4468. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4469. disconnect(self.on_excellon_zeros_changed)
  4470. except TypeError:
  4471. pass
  4472. def on_excellon_format_changed(self):
  4473. """
  4474. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  4475. :return: None
  4476. """
  4477. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  4478. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4479. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  4480. )
  4481. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4482. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  4483. )
  4484. else:
  4485. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4486. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  4487. )
  4488. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4489. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  4490. )
  4491. def on_excellon_zeros_changed(self):
  4492. """
  4493. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  4494. :return: None
  4495. """
  4496. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  4497. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  4498. )
  4499. def on_excellon_units_changed(self):
  4500. """
  4501. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  4502. :return: None
  4503. """
  4504. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  4505. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  4506. )
  4507. self.on_excellon_format_changed()
  4508. # Setting plot colors handlers
  4509. def on_pf_color_entry(self):
  4510. self.defaults['global_plot_fill'] = \
  4511. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  4512. self.defaults['global_plot_fill'][7:9]
  4513. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4514. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  4515. def on_pf_color_button(self):
  4516. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  4517. c_dialog = QtWidgets.QColorDialog()
  4518. plot_fill_color = c_dialog.getColor(initial=current_color)
  4519. if plot_fill_color.isValid() is False:
  4520. return
  4521. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4522. "background-color:%s" % str(plot_fill_color.name()))
  4523. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  4524. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  4525. self.defaults['global_plot_fill'] = new_val
  4526. def on_pf_color_spinner(self):
  4527. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  4528. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  4529. self.defaults['global_plot_fill'] = \
  4530. self.defaults['global_plot_fill'][:7] + \
  4531. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4532. self.defaults['global_plot_line'] = \
  4533. self.defaults['global_plot_line'][:7] + \
  4534. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4535. def on_pf_color_slider(self):
  4536. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  4537. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  4538. def on_pl_color_entry(self):
  4539. self.defaults['global_plot_line'] = \
  4540. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  4541. self.defaults['global_plot_line'][7:9]
  4542. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4543. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  4544. def on_pl_color_button(self):
  4545. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  4546. # print(current_color)
  4547. c_dialog = QtWidgets.QColorDialog()
  4548. plot_line_color = c_dialog.getColor(initial=current_color)
  4549. if plot_line_color.isValid() is False:
  4550. return
  4551. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4552. "background-color:%s" % str(plot_line_color.name()))
  4553. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  4554. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  4555. self.defaults['global_plot_line'] = new_val_line
  4556. # Setting selection colors (left - right) handlers
  4557. def on_sf_color_entry(self):
  4558. self.defaults['global_sel_fill'] = \
  4559. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  4560. self.defaults['global_sel_fill'][7:9]
  4561. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4562. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  4563. def on_sf_color_button(self):
  4564. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  4565. c_dialog = QtWidgets.QColorDialog()
  4566. plot_fill_color = c_dialog.getColor(initial=current_color)
  4567. if plot_fill_color.isValid() is False:
  4568. return
  4569. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4570. "background-color:%s" % str(plot_fill_color.name()))
  4571. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  4572. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  4573. self.defaults['global_sel_fill'] = new_val
  4574. def on_sf_color_spinner(self):
  4575. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  4576. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  4577. self.defaults['global_sel_fill'] = \
  4578. self.defaults['global_sel_fill'][:7] + \
  4579. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4580. self.defaults['global_sel_line'] = \
  4581. self.defaults['global_sel_line'][:7] + \
  4582. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4583. def on_sf_color_slider(self):
  4584. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  4585. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  4586. def on_sl_color_entry(self):
  4587. self.defaults['global_sel_line'] = \
  4588. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  4589. self.defaults['global_sel_line'][7:9]
  4590. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4591. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  4592. def on_sl_color_button(self):
  4593. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  4594. c_dialog = QtWidgets.QColorDialog()
  4595. plot_line_color = c_dialog.getColor(initial=current_color)
  4596. if plot_line_color.isValid() is False:
  4597. return
  4598. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4599. "background-color:%s" % str(plot_line_color.name()))
  4600. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  4601. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  4602. self.defaults['global_sel_line'] = new_val_line
  4603. # Setting selection colors (right - left) handlers
  4604. def on_alt_sf_color_entry(self):
  4605. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  4606. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  4607. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4608. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  4609. def on_alt_sf_color_button(self):
  4610. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  4611. c_dialog = QtWidgets.QColorDialog()
  4612. plot_fill_color = c_dialog.getColor(initial=current_color)
  4613. if plot_fill_color.isValid() is False:
  4614. return
  4615. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4616. "background-color:%s" % str(plot_fill_color.name()))
  4617. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  4618. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  4619. self.defaults['global_alt_sel_fill'] = new_val
  4620. def on_alt_sf_color_spinner(self):
  4621. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  4622. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  4623. self.defaults['global_alt_sel_fill'] = \
  4624. self.defaults['global_alt_sel_fill'][:7] + \
  4625. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4626. self.defaults['global_alt_sel_line'] = \
  4627. self.defaults['global_alt_sel_line'][:7] + \
  4628. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4629. def on_alt_sf_color_slider(self):
  4630. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  4631. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  4632. def on_alt_sl_color_entry(self):
  4633. self.defaults['global_alt_sel_line'] = \
  4634. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  4635. self.defaults['global_alt_sel_line'][7:9]
  4636. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4637. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  4638. def on_alt_sl_color_button(self):
  4639. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  4640. c_dialog = QtWidgets.QColorDialog()
  4641. plot_line_color = c_dialog.getColor(initial=current_color)
  4642. if plot_line_color.isValid() is False:
  4643. return
  4644. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  4645. "background-color:%s" % str(plot_line_color.name()))
  4646. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  4647. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  4648. self.defaults['global_alt_sel_line'] = new_val_line
  4649. # Setting Editor colors
  4650. def on_draw_color_entry(self):
  4651. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4652. .draw_color_entry.get_value()
  4653. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4654. "background-color:%s" % str(self.defaults['global_draw_color']))
  4655. def on_draw_color_button(self):
  4656. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  4657. c_dialog = QtWidgets.QColorDialog()
  4658. draw_color = c_dialog.getColor(initial=current_color)
  4659. if draw_color.isValid() is False:
  4660. return
  4661. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  4662. "background-color:%s" % str(draw_color.name()))
  4663. new_val = str(draw_color.name())
  4664. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  4665. self.defaults['global_draw_color'] = new_val
  4666. def on_sel_draw_color_entry(self):
  4667. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  4668. .sel_draw_color_entry.get_value()
  4669. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4670. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  4671. def on_sel_draw_color_button(self):
  4672. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  4673. c_dialog = QtWidgets.QColorDialog()
  4674. sel_draw_color = c_dialog.getColor(initial=current_color)
  4675. if sel_draw_color.isValid() is False:
  4676. return
  4677. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  4678. "background-color:%s" % str(sel_draw_color.name()))
  4679. new_val_sel = str(sel_draw_color.name())
  4680. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  4681. self.defaults['global_sel_draw_color'] = new_val_sel
  4682. def on_proj_color_entry(self):
  4683. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  4684. .proj_color_entry.get_value()
  4685. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4686. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  4687. def on_proj_color_button(self):
  4688. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  4689. c_dialog = QtWidgets.QColorDialog()
  4690. proj_color = c_dialog.getColor(initial=current_color)
  4691. if proj_color.isValid() is False:
  4692. return
  4693. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  4694. "background-color:%s" % str(proj_color.name()))
  4695. new_val_sel = str(proj_color.name())
  4696. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  4697. self.defaults['global_proj_item_color'] = new_val_sel
  4698. def on_proj_color_dis_entry(self):
  4699. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  4700. .proj_color_dis_entry.get_value()
  4701. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4702. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  4703. def on_proj_color_dis_button(self):
  4704. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  4705. c_dialog = QtWidgets.QColorDialog()
  4706. proj_color = c_dialog.getColor(initial=current_color)
  4707. if proj_color.isValid() is False:
  4708. return
  4709. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  4710. "background-color:%s" % str(proj_color.name()))
  4711. new_val_sel = str(proj_color.name())
  4712. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  4713. self.defaults['global_proj_item_dis_color'] = new_val_sel
  4714. def on_annotation_fontcolor_entry(self):
  4715. self.defaults['cncjob_annotation_fontcolor'] = \
  4716. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  4717. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  4718. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  4719. def on_annotation_fontcolor_button(self):
  4720. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  4721. c_dialog = QtWidgets.QColorDialog()
  4722. annotation_color = c_dialog.getColor(initial=current_color)
  4723. if annotation_color.isValid() is False:
  4724. return
  4725. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  4726. "background-color:%s" % str(annotation_color.name()))
  4727. new_val_sel = str(annotation_color.name())
  4728. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  4729. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  4730. def on_film_color_entry(self):
  4731. self.defaults['tools_film_color'] = \
  4732. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  4733. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  4734. "background-color:%s" % str(self.defaults['tools_film_color']))
  4735. def on_film_color_button(self):
  4736. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  4737. c_dialog = QtWidgets.QColorDialog()
  4738. film_color = c_dialog.getColor(initial=current_color)
  4739. if film_color.isValid() is False:
  4740. return
  4741. # if new color is different then mark that the Preferences are changed
  4742. if film_color != current_color:
  4743. self.on_preferences_edited()
  4744. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  4745. "background-color:%s" % str(film_color.name()))
  4746. new_val_sel = str(film_color.name())
  4747. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  4748. self.defaults['tools_film_color'] = new_val_sel
  4749. def on_splash_changed(self, state):
  4750. settings = QSettings("Open Source", "FlatCAM")
  4751. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  4752. # This will write the setting to the platform specific storage.
  4753. del settings
  4754. def on_notebook_tab_rmb_click(self, checked):
  4755. self.ui.notebook.set_detachable(val=checked)
  4756. self.defaults["global_tabs_detachable"] = checked
  4757. self.ui.plot_tab_area.set_detachable(val=checked)
  4758. self.defaults["global_tabs_detachable"] = checked
  4759. def on_deselect_all(self):
  4760. self.collection.set_all_inactive()
  4761. self.delete_selection_shape()
  4762. def on_workspace_modified(self):
  4763. self.save_defaults(silent=True)
  4764. self.plotcanvas.draw_workspace()
  4765. def on_workspace(self):
  4766. self.report_usage("on_workspace()")
  4767. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  4768. self.plotcanvas.restore_workspace()
  4769. else:
  4770. self.plotcanvas.delete_workspace()
  4771. self.save_defaults(silent=True)
  4772. def on_workspace_menu(self):
  4773. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  4774. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  4775. else:
  4776. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  4777. self.on_workspace()
  4778. def on_layout(self, index=None, lay=None):
  4779. self.report_usage("on_layout()")
  4780. if lay:
  4781. current_layout = lay
  4782. else:
  4783. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  4784. settings = QSettings("Open Source", "FlatCAM")
  4785. settings.setValue('layout', current_layout)
  4786. # This will write the setting to the platform specific storage.
  4787. del settings
  4788. # first remove the toolbars:
  4789. try:
  4790. self.ui.removeToolBar(self.ui.toolbarfile)
  4791. self.ui.removeToolBar(self.ui.toolbargeo)
  4792. self.ui.removeToolBar(self.ui.toolbarview)
  4793. self.ui.removeToolBar(self.ui.toolbarshell)
  4794. self.ui.removeToolBar(self.ui.toolbartools)
  4795. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  4796. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  4797. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  4798. self.ui.removeToolBar(self.ui.snap_toolbar)
  4799. self.ui.removeToolBar(self.ui.toolbarshell)
  4800. except Exception as e:
  4801. pass
  4802. if current_layout == 'standard':
  4803. # ## TOOLBAR INSTALLATION # ##
  4804. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4805. self.ui.toolbarfile.setObjectName('File_TB')
  4806. self.ui.addToolBar(self.ui.toolbarfile)
  4807. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4808. self.ui.toolbargeo.setObjectName('Edit_TB')
  4809. self.ui.addToolBar(self.ui.toolbargeo)
  4810. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4811. self.ui.toolbarview.setObjectName('View_TB')
  4812. self.ui.addToolBar(self.ui.toolbarview)
  4813. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4814. self.ui.toolbarshell.setObjectName('Shell_TB')
  4815. self.ui.addToolBar(self.ui.toolbarshell)
  4816. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4817. self.ui.toolbartools.setObjectName('Tools_TB')
  4818. self.ui.addToolBar(self.ui.toolbartools)
  4819. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4820. # self.ui.exc_edit_toolbar.setVisible(False)
  4821. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4822. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  4823. self.ui.addToolBarBreak()
  4824. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4825. # self.ui.geo_edit_toolbar.setVisible(False)
  4826. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4827. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  4828. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4829. # self.ui.grb_edit_toolbar.setVisible(False)
  4830. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4831. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  4832. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4833. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4834. # self.ui.snap_toolbar.setMaximumHeight(30)
  4835. self.ui.addToolBar(self.ui.snap_toolbar)
  4836. self.ui.corner_snap_btn.setVisible(False)
  4837. self.ui.snap_magnet.setVisible(False)
  4838. elif current_layout == 'compact':
  4839. # ## TOOLBAR INSTALLATION # ##
  4840. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  4841. self.ui.toolbarfile.setObjectName('File_TB')
  4842. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  4843. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  4844. self.ui.toolbargeo.setObjectName('Edit_TB')
  4845. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  4846. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  4847. self.ui.toolbarshell.setObjectName('Shell_TB')
  4848. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  4849. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  4850. self.ui.toolbartools.setObjectName('Tools_TB')
  4851. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  4852. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  4853. # self.ui.geo_edit_toolbar.setVisible(False)
  4854. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  4855. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  4856. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  4857. self.ui.toolbarview.setObjectName('View_TB')
  4858. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  4859. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  4860. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  4861. # self.ui.grb_edit_toolbar.setVisible(False)
  4862. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  4863. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  4864. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  4865. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  4866. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  4867. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  4868. self.ui.snap_toolbar.setObjectName('Snap_TB')
  4869. self.ui.snap_toolbar.setMaximumHeight(30)
  4870. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  4871. self.ui.corner_snap_btn.setVisible(True)
  4872. self.ui.snap_magnet.setVisible(True)
  4873. # add all the actions to the toolbars
  4874. self.ui.populate_toolbars()
  4875. # reconnect all the signals to the toolbar actions
  4876. self.connect_toolbar_signals()
  4877. self.ui.grid_snap_btn.setChecked(True)
  4878. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  4879. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  4880. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  4881. self.ui.grid_gap_link_cb.setChecked(True)
  4882. def on_cnc_custom_parameters(self, signal_text):
  4883. if signal_text == 'Parameters':
  4884. return
  4885. else:
  4886. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  4887. def on_save_button(self):
  4888. log.debug("App.on_save_button() --> Saving preferences to file.")
  4889. self.preferences_changed_flag = False
  4890. self.save_defaults(silent=False)
  4891. # load the defaults so they are updated into the app
  4892. self.load_defaults(filename='current_defaults')
  4893. # Re-fresh project options
  4894. self.on_options_app2project()
  4895. # save the notebook font size
  4896. settings = QSettings("Open Source", "FlatCAM")
  4897. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  4898. settings.setValue('notebook_font_size', fsize)
  4899. # save the axis font size
  4900. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  4901. settings.setValue('axis_font_size', g_fsize)
  4902. # This will write the setting to the platform specific storage.
  4903. del settings
  4904. def handlePrint(self):
  4905. self.report_usage("handlePrint()")
  4906. dialog = QtPrintSupport.QPrintDialog()
  4907. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  4908. self.ui.code_editor.document().print_(dialog.printer())
  4909. def handlePreview(self):
  4910. self.report_usage("handlePreview()")
  4911. dialog = QtPrintSupport.QPrintPreviewDialog()
  4912. dialog.paintRequested.connect(self.ui.code_editor.print_)
  4913. dialog.exec_()
  4914. def handleTextChanged(self):
  4915. # enable = not self.ui.code_editor.document().isEmpty()
  4916. # self.ui.buttonPrint.setEnabled(enable)
  4917. # self.ui.buttonPreview.setEnabled(enable)
  4918. pass
  4919. def handleOpen(self, filt=None):
  4920. self.report_usage("handleOpen()")
  4921. if filt:
  4922. _filter_ = filt
  4923. else:
  4924. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4925. "All Files (*.*)"
  4926. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  4927. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  4928. if path:
  4929. file = QtCore.QFile(path)
  4930. if file.open(QtCore.QIODevice.ReadOnly):
  4931. stream = QtCore.QTextStream(file)
  4932. self.gcode_edited = stream.readAll()
  4933. self.ui.code_editor.setPlainText(self.gcode_edited)
  4934. file.close()
  4935. def handleSaveGCode(self, name=None, filt=None):
  4936. self.report_usage("handleSaveGCode()")
  4937. if filt:
  4938. _filter_ = filt
  4939. else:
  4940. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  4941. "All Files (*.*)"
  4942. if name:
  4943. obj_name = name
  4944. else:
  4945. try:
  4946. obj_name = self.collection.get_active().options['name']
  4947. except AttributeError:
  4948. obj_name = 'file'
  4949. if filt is None:
  4950. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  4951. try:
  4952. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  4953. caption=_("Export G-Code ..."),
  4954. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  4955. filter=_filter_
  4956. )[0])
  4957. except TypeError:
  4958. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  4959. if filename == "":
  4960. self.inform.emit('[WARNING_NOTCL] %s' %
  4961. _("Export Code cancelled."))
  4962. return
  4963. else:
  4964. try:
  4965. my_gcode = self.ui.code_editor.toPlainText()
  4966. with open(filename, 'w') as f:
  4967. for line in my_gcode:
  4968. f.write(line)
  4969. except FileNotFoundError:
  4970. self.inform.emit('[WARNING] %s' %
  4971. _("No such file or directory"))
  4972. return
  4973. except PermissionError:
  4974. self.inform.emit('[WARNING] %s' %
  4975. _("Permission denied, saving not possible.\n"
  4976. "Most likely another app is holding the file open and not accessible."))
  4977. return
  4978. # Just for adding it to the recent files list.
  4979. if self.defaults["global_open_style"] is False:
  4980. self.file_opened.emit("cncjob", filename)
  4981. self.file_saved.emit("cncjob", filename)
  4982. self.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  4983. def handleFindGCode(self):
  4984. self.report_usage("handleFindGCode()")
  4985. flags = QtGui.QTextDocument.FindCaseSensitively
  4986. text_to_be_found = self.ui.entryFind.get_value()
  4987. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  4988. if r is False:
  4989. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4990. def handleReplaceGCode(self):
  4991. self.report_usage("handleReplaceGCode()")
  4992. old = self.ui.entryFind.get_value()
  4993. new = self.ui.entryReplace.get_value()
  4994. if self.ui.sel_all_cb.isChecked():
  4995. while True:
  4996. cursor = self.ui.code_editor.textCursor()
  4997. cursor.beginEditBlock()
  4998. flags = QtGui.QTextDocument.FindCaseSensitively
  4999. # self.ui.editor is the QPlainTextEdit
  5000. r = self.ui.code_editor.find(str(old), flags)
  5001. if r:
  5002. qc = self.ui.code_editor.textCursor()
  5003. if qc.hasSelection():
  5004. qc.insertText(new)
  5005. else:
  5006. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5007. break
  5008. # Mark end of undo block
  5009. cursor.endEditBlock()
  5010. else:
  5011. cursor = self.ui.code_editor.textCursor()
  5012. cursor.beginEditBlock()
  5013. qc = self.ui.code_editor.textCursor()
  5014. if qc.hasSelection():
  5015. qc.insertText(new)
  5016. # Mark end of undo block
  5017. cursor.endEditBlock()
  5018. def handleRunCode(self):
  5019. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  5020. # tries to print on a hidden widget, therefore show the dock if hidden
  5021. if self.ui.shell_dock.isHidden():
  5022. self.ui.shell_dock.show()
  5023. self.script_code = deepcopy(self.ui.code_editor.toPlainText())
  5024. # self.shell._sysShell.exec_command(script_code)
  5025. old_line = ''
  5026. for tcl_command_line in self.script_code.splitlines():
  5027. # do not process lines starting with '#' = comment and empty lines
  5028. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  5029. # id FlatCAM is run in Windows then replace all the slashes with
  5030. # the UNIX style slash that TCL understands
  5031. if sys.platform == 'win32':
  5032. if "open" in tcl_command_line:
  5033. tcl_command_line = tcl_command_line.replace('\\', '/')
  5034. if old_line != '':
  5035. new_command = old_line + tcl_command_line + '\n'
  5036. else:
  5037. new_command = tcl_command_line
  5038. # execute the actual Tcl command
  5039. try:
  5040. self.shell.open_proccessing() # Disables input box.
  5041. result = self.tcl.eval(str(new_command))
  5042. if result != 'None':
  5043. self.shell.append_output(result + '\n')
  5044. old_line = ''
  5045. except tk.TclError:
  5046. old_line = old_line + tcl_command_line + '\n'
  5047. except Exception as e:
  5048. log.debug("App.handleRunCode() --> %s" % str(e))
  5049. if old_line != '':
  5050. # it means that the script finished with an error
  5051. result = self.tcl.eval("set errorInfo")
  5052. self.log.error("Exec command Exception: %s" % (result + '\n'))
  5053. self.shell.append_error('ERROR: ' + result + '\n')
  5054. self.shell.close_proccessing()
  5055. def on_tool_add_keypress(self):
  5056. # ## Current application units in Upper Case
  5057. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5058. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5059. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5060. if notebook_widget_name == 'selected_tab':
  5061. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5062. # Tool add works for Geometry only if Advanced is True in Preferences
  5063. if self.defaults["global_app_level"] == 'a':
  5064. tool_add_popup = FCInputDialog(title="New Tool ...",
  5065. text='Enter a Tool Diameter:',
  5066. min=0.0000, max=99.9999, decimals=4)
  5067. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5068. val, ok = tool_add_popup.get_value()
  5069. if ok:
  5070. if float(val) == 0:
  5071. self.inform.emit('[WARNING_NOTCL] %s' %
  5072. _("Please enter a tool diameter with non-zero value, in Float format."))
  5073. return
  5074. self.collection.get_active().on_tool_add(dia=float(val))
  5075. else:
  5076. self.inform.emit('[WARNING_NOTCL] %s...' %
  5077. _("Adding Tool cancelled"))
  5078. else:
  5079. msgbox = QtWidgets.QMessageBox()
  5080. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5081. "Go to Preferences -> General - Show Advanced Options."))
  5082. msgbox.setWindowTitle("Tool adding ...")
  5083. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5084. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5085. msgbox.setDefaultButton(bt_ok)
  5086. msgbox.exec_()
  5087. # work only if the notebook tab on focus is the Tools_Tab
  5088. if notebook_widget_name == 'tool_tab':
  5089. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5090. tool_add_popup = FCInputDialog(title="New Tool ...",
  5091. text='Enter a Tool Diameter:',
  5092. min=0.0000, max=99.9999, decimals=4)
  5093. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5094. val, ok = tool_add_popup.get_value()
  5095. # and only if the tool is NCC Tool
  5096. if tool_widget == self.ncclear_tool.toolName:
  5097. if ok:
  5098. if float(val) == 0:
  5099. self.inform.emit('[WARNING_NOTCL] %s' %
  5100. _("Please enter a tool diameter with non-zero value, in Float format."))
  5101. return
  5102. self.ncclear_tool.on_tool_add(dia=float(val))
  5103. else:
  5104. self.inform.emit('[WARNING_NOTCL] %s...' %
  5105. _("Adding Tool cancelled"))
  5106. # and only if the tool is Paint Area Tool
  5107. elif tool_widget == self.paint_tool.toolName:
  5108. if ok:
  5109. if float(val) == 0:
  5110. self.inform.emit('[WARNING_NOTCL] %s' %
  5111. _("Please enter a tool diameter with non-zero value, in Float format."))
  5112. return
  5113. self.paint_tool.on_tool_add(dia=float(val))
  5114. else:
  5115. self.inform.emit('[WARNING_NOTCL] %s...' %
  5116. _("Adding Tool cancelled"))
  5117. # and only if the tool is Solder Paste Dispensing Tool
  5118. elif tool_widget == self.paste_tool.toolName:
  5119. if ok:
  5120. if float(val) == 0:
  5121. self.inform.emit('[WARNING_NOTCL] %s' %
  5122. _("Please enter a tool diameter with non-zero value, in Float format."))
  5123. return
  5124. self.paste_tool.on_tool_add(dia=float(val))
  5125. else:
  5126. self.inform.emit('[WARNING_NOTCL] %s...' %
  5127. _("Adding Tool cancelled"))
  5128. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5129. # See description bellow.
  5130. def on_delete_keypress(self):
  5131. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5132. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5133. if notebook_widget_name == 'selected_tab':
  5134. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5135. self.collection.get_active().on_tool_delete()
  5136. # work only if the notebook tab on focus is the Tools_Tab
  5137. elif notebook_widget_name == 'tool_tab':
  5138. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5139. # and only if the tool is NCC Tool
  5140. if tool_widget == self.ncclear_tool.toolName:
  5141. self.ncclear_tool.on_tool_delete()
  5142. # and only if the tool is Paint Tool
  5143. elif tool_widget == self.paint_tool.toolName:
  5144. self.paint_tool.on_tool_delete()
  5145. # and only if the tool is Solder Paste Dispensing Tool
  5146. elif tool_widget == self.paste_tool.toolName:
  5147. self.paste_tool.on_tool_delete()
  5148. else:
  5149. self.on_delete()
  5150. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5151. # some screens you have to be careful where you hover with your mouse.
  5152. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5153. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5154. # Complicated, I know :)
  5155. def on_delete(self):
  5156. """
  5157. Delete the currently selected FlatCAMObjs.
  5158. :return: None
  5159. """
  5160. self.report_usage("on_delete()")
  5161. response = None
  5162. bt_ok = None
  5163. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5164. # a geometry object before we update it.
  5165. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5166. and self.grb_editor.editor_active is False:
  5167. if self.defaults["global_delete_confirmation"] is True:
  5168. msgbox = QtWidgets.QMessageBox()
  5169. msgbox.setWindowTitle(_("Delete objects"))
  5170. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5171. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5172. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5173. "the selected objects?"))
  5174. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5175. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5176. msgbox.setDefaultButton(bt_ok)
  5177. msgbox.exec_()
  5178. response = msgbox.clickedButton()
  5179. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5180. if self.collection.get_active():
  5181. self.log.debug("App.on_delete()")
  5182. while self.collection.get_active():
  5183. obj_active = self.collection.get_active()
  5184. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5185. if isinstance(obj_active, FlatCAMGerber):
  5186. for el in obj_active.mark_shapes:
  5187. obj_active.mark_shapes[el].clear(update=True)
  5188. obj_active.mark_shapes[el].enabled = False
  5189. # obj_active.mark_shapes[el] = None
  5190. del el
  5191. elif isinstance(obj_active, FlatCAMCNCjob):
  5192. try:
  5193. obj_active.annotation.clear(update=True)
  5194. obj_active.annotation.enabled = False
  5195. except AttributeError:
  5196. pass
  5197. self.delete_first_selected()
  5198. self.inform.emit('%s...' %
  5199. _("Object(s) deleted"))
  5200. # make sure that the selection shape is deleted, too
  5201. self.delete_selection_shape()
  5202. else:
  5203. self.inform.emit(_("Failed. No object(s) selected..."))
  5204. else:
  5205. self.inform.emit(_("Save the work in Editor and try again ..."))
  5206. def delete_first_selected(self):
  5207. # Keep this for later
  5208. try:
  5209. sel_obj = self.collection.get_active()
  5210. name = sel_obj.options["name"]
  5211. except AttributeError:
  5212. self.log.debug("Nothing selected for deletion")
  5213. return
  5214. # Remove from dictionary
  5215. self.collection.delete_active()
  5216. # Clear form
  5217. self.setup_component_editor()
  5218. self.inform.emit('%s: %s' %
  5219. (_("Object deleted"), name))
  5220. def on_set_origin(self):
  5221. """
  5222. Set the origin to the left mouse click position
  5223. :return: None
  5224. """
  5225. # display the message for the user
  5226. # and ask him to click on the desired position
  5227. self.report_usage("on_set_origin()")
  5228. def origin_replot():
  5229. def worker_task():
  5230. with self.proc_container.new('%s...' % _("Plotting")):
  5231. for obj in self.collection.get_list():
  5232. obj.plot()
  5233. self.plotcanvas.fit_view()
  5234. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  5235. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5236. self.inform.emit(_('Click to set the origin ...'))
  5237. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  5238. # first disconnect it as it may have been used by something else
  5239. try:
  5240. self.replot_signal.disconnect()
  5241. except TypeError:
  5242. pass
  5243. self.replot_signal[list].connect(origin_replot)
  5244. def on_set_zero_click(self, event):
  5245. # this function will be available only for mouse left click
  5246. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5247. if event.button == 1:
  5248. if self.grid_status() == True:
  5249. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5250. else:
  5251. pos = pos_canvas
  5252. x = 0 - pos[0]
  5253. y = 0 - pos[1]
  5254. def worker_task():
  5255. with self.proc_container.new(_("Setting Origin...")):
  5256. for obj in self.collection.get_list():
  5257. obj.offset((x, y))
  5258. self.object_changed.emit(obj)
  5259. # Update the object bounding box options
  5260. a, b, c, d = obj.bounds()
  5261. obj.options['xmin'] = a
  5262. obj.options['ymin'] = b
  5263. obj.options['xmax'] = c
  5264. obj.options['ymax'] = d
  5265. self.inform.emit('[success]%s...' %
  5266. _('Origin set'))
  5267. self.replot_signal.emit([])
  5268. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5269. self.should_we_save = True
  5270. def on_jump_to(self, custom_location=None, fit_center=True):
  5271. """
  5272. Jump to a location by setting the mouse cursor location
  5273. :return:
  5274. """
  5275. self.report_usage("on_jump_to()")
  5276. if not custom_location:
  5277. dia_box = Dialog_box(title=_("Jump to ..."),
  5278. label=_("Enter the coordinates in format X,Y:"),
  5279. icon=QtGui.QIcon('share/jump_to16.png'))
  5280. if dia_box.ok is True:
  5281. try:
  5282. location = eval(dia_box.location)
  5283. if not isinstance(location, tuple):
  5284. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5285. return
  5286. except:
  5287. return
  5288. else:
  5289. return
  5290. else:
  5291. location = custom_location
  5292. if fit_center:
  5293. self.plotcanvas.fit_center(loc=location)
  5294. cursor = QtGui.QCursor()
  5295. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5296. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5297. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5298. self.inform.emit('[success] %s' %
  5299. _("Done."))
  5300. return location
  5301. def on_copy_object(self):
  5302. self.report_usage("on_copy_object()")
  5303. def initialize(obj_init, app):
  5304. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5305. try:
  5306. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5307. except AttributeError:
  5308. pass
  5309. try:
  5310. obj_init.apertures = deepcopy(obj.apertures)
  5311. except AttributeError:
  5312. pass
  5313. try:
  5314. if obj.tools:
  5315. obj_init.tools = deepcopy(obj.tools)
  5316. except Exception as e:
  5317. log.debug("App.on_copy_object() --> %s" % str(e))
  5318. def initialize_excellon(obj_init, app):
  5319. obj_init.tools = deepcopy(obj.tools)
  5320. # drills are offset, so they need to be deep copied
  5321. obj_init.drills = deepcopy(obj.drills)
  5322. # slots are offset, so they need to be deep copied
  5323. obj_init.slots = deepcopy(obj.slots)
  5324. obj_init.create_geometry()
  5325. for obj in self.collection.get_selected():
  5326. obj_name = obj.options["name"]
  5327. try:
  5328. if isinstance(obj, FlatCAMExcellon):
  5329. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5330. elif isinstance(obj, FlatCAMGerber):
  5331. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5332. elif isinstance(obj, FlatCAMGeometry):
  5333. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5334. except Exception as e:
  5335. return "Operation failed: %s" % str(e)
  5336. def on_copy_object2(self, custom_name):
  5337. def initialize_geometry(obj_init, app):
  5338. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5339. try:
  5340. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5341. except AttributeError:
  5342. pass
  5343. try:
  5344. obj_init.apertures = deepcopy(obj.apertures)
  5345. except AttributeError:
  5346. pass
  5347. try:
  5348. if obj.tools:
  5349. obj_init.tools = deepcopy(obj.tools)
  5350. except Exception as e:
  5351. log.debug("on_copy_object2() --> %s" % str(e))
  5352. def initialize_gerber(obj_init, app):
  5353. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5354. obj_init.apertures = deepcopy(obj.apertures)
  5355. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5356. def initialize_excellon(obj_init, app):
  5357. obj_init.tools = deepcopy(obj.tools)
  5358. # drills are offset, so they need to be deep copied
  5359. obj_init.drills = deepcopy(obj.drills)
  5360. # slots are offset, so they need to be deep copied
  5361. obj_init.slots = deepcopy(obj.slots)
  5362. obj_init.create_geometry()
  5363. for obj in self.collection.get_selected():
  5364. obj_name = obj.options["name"]
  5365. try:
  5366. if isinstance(obj, FlatCAMExcellon):
  5367. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5368. elif isinstance(obj, FlatCAMGerber):
  5369. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5370. elif isinstance(obj, FlatCAMGeometry):
  5371. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5372. except Exception as e:
  5373. return "Operation failed: %s" % str(e)
  5374. def on_rename_object(self, text):
  5375. self.report_usage("on_rename_object()")
  5376. named_obj = self.collection.get_active()
  5377. for obj in named_obj:
  5378. if obj is list:
  5379. self.on_rename_object(text)
  5380. else:
  5381. try:
  5382. obj.options['name'] = text
  5383. except Exception as e:
  5384. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5385. def convert_any2geo(self):
  5386. self.report_usage("convert_any2geo()")
  5387. def initialize(obj_init, app):
  5388. obj_init.solid_geometry = obj.solid_geometry
  5389. try:
  5390. obj_init.follow_geometry = obj.follow_geometry
  5391. except AttributeError:
  5392. pass
  5393. try:
  5394. obj_init.apertures = obj.apertures
  5395. except AttributeError:
  5396. pass
  5397. try:
  5398. if obj.tools:
  5399. obj_init.tools = obj.tools
  5400. except AttributeError:
  5401. pass
  5402. def initialize_excellon(obj_init, app):
  5403. # objs = self.collection.get_selected()
  5404. # FlatCAMGeometry.merge(objs, obj)
  5405. solid_geo = []
  5406. for tool in obj.tools:
  5407. for geo in obj.tools[tool]['solid_geometry']:
  5408. solid_geo.append(geo)
  5409. obj_init.solid_geometry = deepcopy(solid_geo)
  5410. if not self.collection.get_selected():
  5411. log.warning("App.convert_any2geo --> No object selected")
  5412. self.inform.emit('[WARNING_NOTCL] %s' %
  5413. _("No object is selected. Select an object and try again."))
  5414. return
  5415. for obj in self.collection.get_selected():
  5416. obj_name = obj.options["name"]
  5417. try:
  5418. if isinstance(obj, FlatCAMExcellon):
  5419. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5420. else:
  5421. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5422. except Exception as e:
  5423. return "Operation failed: %s" % str(e)
  5424. def convert_any2gerber(self):
  5425. self.report_usage("convert_any2gerber()")
  5426. def initialize_geometry(obj_init, app):
  5427. apertures = {}
  5428. apid = 0
  5429. apertures[str(apid)] = {}
  5430. apertures[str(apid)]['geometry'] = []
  5431. for obj_orig in obj.solid_geometry:
  5432. new_elem = dict()
  5433. new_elem['solid'] = obj_orig
  5434. new_elem['follow'] = obj_orig.exterior
  5435. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5436. apertures[str(apid)]['size'] = 0.0
  5437. apertures[str(apid)]['type'] = 'C'
  5438. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5439. obj_init.apertures = deepcopy(apertures)
  5440. def initialize_excellon(obj_init, app):
  5441. apertures = {}
  5442. apid = 10
  5443. for tool in obj.tools:
  5444. apertures[str(apid)] = {}
  5445. apertures[str(apid)]['geometry'] = []
  5446. for geo in obj.tools[tool]['solid_geometry']:
  5447. new_el = dict()
  5448. new_el['solid'] = geo
  5449. new_el['follow'] = geo.exterior
  5450. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5451. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5452. apertures[str(apid)]['type'] = 'C'
  5453. apid += 1
  5454. # create solid_geometry
  5455. solid_geometry = []
  5456. for apid in apertures:
  5457. for geo_el in apertures[apid]['geometry']:
  5458. solid_geometry.append(geo_el['solid'])
  5459. solid_geometry = MultiPolygon(solid_geometry)
  5460. solid_geometry = solid_geometry.buffer(0.0000001)
  5461. obj_init.solid_geometry = deepcopy(solid_geometry)
  5462. obj_init.apertures = deepcopy(apertures)
  5463. # clear the working objects (perhaps not necessary due of Python GC)
  5464. apertures.clear()
  5465. if not self.collection.get_selected():
  5466. log.warning("App.convert_any2gerber --> No object selected")
  5467. self.inform.emit('[WARNING_NOTCL] %s' %
  5468. _("No object is selected. Select an object and try again."))
  5469. return
  5470. for obj in self.collection.get_selected():
  5471. obj_name = obj.options["name"]
  5472. try:
  5473. if isinstance(obj, FlatCAMExcellon):
  5474. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  5475. elif isinstance(obj, FlatCAMGeometry):
  5476. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  5477. else:
  5478. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  5479. except Exception as e:
  5480. return "Operation failed: %s" % str(e)
  5481. def abort_all_tasks(self):
  5482. if self.abort_flag is False:
  5483. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  5484. self.abort_flag = True
  5485. def app_is_idle(self):
  5486. if self.abort_flag:
  5487. self.inform.emit('[WARNING_NOTCL] %s' %
  5488. _("The current task was gracefully closed on user request..."))
  5489. self.abort_flag = False
  5490. def on_selectall(self):
  5491. self.report_usage("on_selectall()")
  5492. # delete the possible selection box around a possible selected object
  5493. self.delete_selection_shape()
  5494. for name in self.collection.get_names():
  5495. self.collection.set_active(name)
  5496. curr_sel_obj = self.collection.get_by_name(name)
  5497. # create the selection box around the selected object
  5498. if self.defaults['global_selection_shape'] is True:
  5499. self.draw_selection_shape(curr_sel_obj)
  5500. def on_preferences(self):
  5501. # add the tab if it was closed
  5502. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  5503. # delete the absolute and relative position and messages in the infobar
  5504. self.ui.position_label.setText("")
  5505. self.ui.rel_position_label.setText("")
  5506. # Switch plot_area to preferences page
  5507. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  5508. # self.ui.show()
  5509. # this disconnect() is done so the slot will be connected only once
  5510. try:
  5511. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  5512. except (TypeError, AttributeError):
  5513. pass
  5514. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  5515. # detect changes in the preferences
  5516. for idx in range(self.ui.pref_tab_area.count()):
  5517. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5518. try:
  5519. try:
  5520. tb.textEdited.disconnect(self.on_preferences_edited)
  5521. except (TypeError, AttributeError):
  5522. pass
  5523. tb.textEdited.connect(self.on_preferences_edited)
  5524. except AttributeError:
  5525. pass
  5526. try:
  5527. try:
  5528. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5529. except (TypeError, AttributeError):
  5530. pass
  5531. tb.modificationChanged.connect(self.on_preferences_edited)
  5532. except AttributeError:
  5533. pass
  5534. try:
  5535. try:
  5536. tb.toggled.disconnect(self.on_preferences_edited)
  5537. except (TypeError, AttributeError):
  5538. pass
  5539. tb.toggled.connect(self.on_preferences_edited)
  5540. except AttributeError:
  5541. pass
  5542. try:
  5543. try:
  5544. tb.valueChanged.disconnect(self.on_preferences_edited)
  5545. except (TypeError, AttributeError):
  5546. pass
  5547. tb.valueChanged.connect(self.on_preferences_edited)
  5548. except AttributeError:
  5549. pass
  5550. try:
  5551. try:
  5552. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5553. except (TypeError, AttributeError):
  5554. pass
  5555. tb.currentIndexChanged.connect(self.on_preferences_edited)
  5556. except AttributeError:
  5557. pass
  5558. def on_preferences_edited(self):
  5559. self.inform.emit('[WARNING_NOTCL] %s' %
  5560. _("Preferences edited but not saved."))
  5561. self.preferences_changed_flag = True
  5562. def on_preferences_closed(self):
  5563. # disconnect
  5564. for idx in range(self.ui.pref_tab_area.count()):
  5565. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5566. try:
  5567. tb.textEdited.disconnect(self.on_preferences_edited)
  5568. except (TypeError, AttributeError):
  5569. pass
  5570. try:
  5571. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5572. except (TypeError, AttributeError):
  5573. pass
  5574. try:
  5575. tb.toggled.disconnect(self.on_preferences_edited)
  5576. except (TypeError, AttributeError):
  5577. pass
  5578. try:
  5579. tb.valueChanged.disconnect(self.on_preferences_edited)
  5580. except (TypeError, AttributeError):
  5581. pass
  5582. try:
  5583. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5584. except (TypeError, AttributeError):
  5585. pass
  5586. if self.preferences_changed_flag is True:
  5587. msgbox = QtWidgets.QMessageBox()
  5588. msgbox.setText(_("One or more values are changed.\n"
  5589. "Do you want to save the Preferences?"))
  5590. msgbox.setWindowTitle(_("Save Preferences"))
  5591. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5592. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5593. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5594. msgbox.setDefaultButton(bt_yes)
  5595. msgbox.exec_()
  5596. response = msgbox.clickedButton()
  5597. if response == bt_yes:
  5598. self.on_save_button()
  5599. self.inform.emit('[success] %s' %
  5600. _("Preferences saved."))
  5601. else:
  5602. self.preferences_changed_flag = False
  5603. return
  5604. def on_flipy(self):
  5605. self.report_usage("on_flipy()")
  5606. obj_list = self.collection.get_selected()
  5607. xminlist = []
  5608. yminlist = []
  5609. xmaxlist = []
  5610. ymaxlist = []
  5611. if not obj_list:
  5612. self.inform.emit('[WARNING_NOTCL] %s' %
  5613. _("No object selected to Flip on Y axis."))
  5614. else:
  5615. try:
  5616. # first get a bounding box to fit all
  5617. for obj in obj_list:
  5618. xmin, ymin, xmax, ymax = obj.bounds()
  5619. xminlist.append(xmin)
  5620. yminlist.append(ymin)
  5621. xmaxlist.append(xmax)
  5622. ymaxlist.append(ymax)
  5623. # get the minimum x,y and maximum x,y for all objects selected
  5624. xminimal = min(xminlist)
  5625. yminimal = min(yminlist)
  5626. xmaximal = max(xmaxlist)
  5627. ymaximal = max(ymaxlist)
  5628. px = 0.5 * (xminimal + xmaximal)
  5629. py = 0.5 * (yminimal + ymaximal)
  5630. # execute mirroring
  5631. for obj in obj_list:
  5632. obj.mirror('X', [px, py])
  5633. obj.plot()
  5634. self.object_changed.emit(obj)
  5635. self.inform.emit('[success] %s' %
  5636. _("Flip on Y axis done."))
  5637. except Exception as e:
  5638. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5639. (_("Flip action was not executed."), str(e)))
  5640. return
  5641. def on_flipx(self):
  5642. self.report_usage("on_flipx()")
  5643. obj_list = self.collection.get_selected()
  5644. xminlist = []
  5645. yminlist = []
  5646. xmaxlist = []
  5647. ymaxlist = []
  5648. if not obj_list:
  5649. self.inform.emit('[WARNING_NOTCL] %s' %
  5650. _("No object selected to Flip on X axis."))
  5651. else:
  5652. try:
  5653. # first get a bounding box to fit all
  5654. for obj in obj_list:
  5655. xmin, ymin, xmax, ymax = obj.bounds()
  5656. xminlist.append(xmin)
  5657. yminlist.append(ymin)
  5658. xmaxlist.append(xmax)
  5659. ymaxlist.append(ymax)
  5660. # get the minimum x,y and maximum x,y for all objects selected
  5661. xminimal = min(xminlist)
  5662. yminimal = min(yminlist)
  5663. xmaximal = max(xmaxlist)
  5664. ymaximal = max(ymaxlist)
  5665. px = 0.5 * (xminimal + xmaximal)
  5666. py = 0.5 * (yminimal + ymaximal)
  5667. # execute mirroring
  5668. for obj in obj_list:
  5669. obj.mirror('Y', [px, py])
  5670. obj.plot()
  5671. self.object_changed.emit(obj)
  5672. self.inform.emit('[success] %s' %
  5673. _("Flip on X axis done."))
  5674. except Exception as e:
  5675. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5676. (_("Flip action was not executed."), str(e)))
  5677. return
  5678. def on_rotate(self, silent=False, preset=None):
  5679. self.report_usage("on_rotate()")
  5680. obj_list = self.collection.get_selected()
  5681. xminlist = []
  5682. yminlist = []
  5683. xmaxlist = []
  5684. ymaxlist = []
  5685. if not obj_list:
  5686. self.inform.emit('[WARNING_NOTCL] %s' %
  5687. _("No object selected to Rotate."))
  5688. else:
  5689. if silent is False:
  5690. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5691. min=-360, max=360, decimals=4,
  5692. init_val=float(self.defaults['tools_transform_rotate']))
  5693. num, ok = rotatebox.get_value()
  5694. else:
  5695. num = preset
  5696. ok = True
  5697. if ok:
  5698. try:
  5699. # first get a bounding box to fit all
  5700. for obj in obj_list:
  5701. xmin, ymin, xmax, ymax = obj.bounds()
  5702. xminlist.append(xmin)
  5703. yminlist.append(ymin)
  5704. xmaxlist.append(xmax)
  5705. ymaxlist.append(ymax)
  5706. # get the minimum x,y and maximum x,y for all objects selected
  5707. xminimal = min(xminlist)
  5708. yminimal = min(yminlist)
  5709. xmaximal = max(xmaxlist)
  5710. ymaximal = max(ymaxlist)
  5711. px = 0.5 * (xminimal + xmaximal)
  5712. py = 0.5 * (yminimal + ymaximal)
  5713. for sel_obj in obj_list:
  5714. sel_obj.rotate(-float(num), point=(px, py))
  5715. sel_obj.plot()
  5716. self.object_changed.emit(sel_obj)
  5717. self.inform.emit('[success] %s' %
  5718. _("Rotation done."))
  5719. except Exception as e:
  5720. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  5721. (_("Rotation movement was not executed."), str(e)))
  5722. return
  5723. def on_skewx(self):
  5724. self.report_usage("on_skewx()")
  5725. obj_list = self.collection.get_selected()
  5726. xminlist = []
  5727. yminlist = []
  5728. if not obj_list:
  5729. self.inform.emit('[WARNING_NOTCL] %s' %
  5730. _("No object selected to Skew/Shear on X axis."))
  5731. else:
  5732. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5733. min=-360, max=360, decimals=4,
  5734. init_val=float(self.defaults['tools_transform_skew_x']))
  5735. num, ok = skewxbox.get_value()
  5736. if ok:
  5737. # first get a bounding box to fit all
  5738. for obj in obj_list:
  5739. xmin, ymin, xmax, ymax = obj.bounds()
  5740. xminlist.append(xmin)
  5741. yminlist.append(ymin)
  5742. # get the minimum x,y and maximum x,y for all objects selected
  5743. xminimal = min(xminlist)
  5744. yminimal = min(yminlist)
  5745. for obj in obj_list:
  5746. obj.skew(num, 0, point=(xminimal, yminimal))
  5747. obj.plot()
  5748. self.object_changed.emit(obj)
  5749. self.inform.emit('[success] %s' %
  5750. _("Skew on X axis done."))
  5751. def on_skewy(self):
  5752. self.report_usage("on_skewy()")
  5753. obj_list = self.collection.get_selected()
  5754. xminlist = []
  5755. yminlist = []
  5756. if not obj_list:
  5757. self.inform.emit('[WARNING_NOTCL] %s' %
  5758. _("No object selected to Skew/Shear on Y axis."))
  5759. else:
  5760. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5761. min=-360, max=360, decimals=4,
  5762. init_val=float(self.defaults['tools_transform_skew_y']))
  5763. num, ok = skewybox.get_value()
  5764. if ok:
  5765. # first get a bounding box to fit all
  5766. for obj in obj_list:
  5767. xmin, ymin, xmax, ymax = obj.bounds()
  5768. xminlist.append(xmin)
  5769. yminlist.append(ymin)
  5770. # get the minimum x,y and maximum x,y for all objects selected
  5771. xminimal = min(xminlist)
  5772. yminimal = min(yminlist)
  5773. for obj in obj_list:
  5774. obj.skew(0, num, point=(xminimal, yminimal))
  5775. obj.plot()
  5776. self.object_changed.emit(obj)
  5777. self.inform.emit('[success] %s' %
  5778. _("Skew on Y axis done."))
  5779. def on_plots_updated(self):
  5780. """
  5781. Callback used to report when the plots have changed.
  5782. Adjust axes and zooms to fit.
  5783. :return: None
  5784. """
  5785. self.plotcanvas.update() # TODO: Need update canvas?
  5786. self.on_zoom_fit(None)
  5787. self.collection.update_view()
  5788. # self.inform.emit(_("Plots updated ..."))
  5789. # TODO: Rework toolbar 'clear', 'replot' functions
  5790. def on_toolbar_replot(self):
  5791. """
  5792. Callback for toolbar button. Re-plots all objects.
  5793. :return: None
  5794. """
  5795. self.report_usage("on_toolbar_replot")
  5796. self.log.debug("on_toolbar_replot()")
  5797. try:
  5798. self.collection.get_active().read_form()
  5799. except AttributeError:
  5800. self.log.debug("on_toolbar_replot(): AttributeError")
  5801. pass
  5802. self.plot_all()
  5803. def on_row_activated(self, index):
  5804. if index.isValid():
  5805. if index.internalPointer().parent_item != self.collection.root_item:
  5806. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5807. self.collection.on_item_activated(index)
  5808. def grid_status(self):
  5809. if self.ui.grid_snap_btn.isChecked():
  5810. return True
  5811. else:
  5812. return False
  5813. def populate_cmenu_grids(self):
  5814. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5815. self.ui.cmenu_gridmenu.clear()
  5816. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5817. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  5818. grid_toggle.setCheckable(True)
  5819. if self.grid_status() == True:
  5820. grid_toggle.setChecked(True)
  5821. else:
  5822. grid_toggle.setChecked(False)
  5823. self.ui.cmenu_gridmenu.addSeparator()
  5824. for grid in sorted_list:
  5825. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  5826. action.triggered.connect(self.set_grid)
  5827. self.ui.cmenu_gridmenu.addSeparator()
  5828. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  5829. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  5830. grid_add.triggered.connect(self.on_grid_add)
  5831. grid_delete.triggered.connect(self.on_grid_delete)
  5832. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5833. def set_grid(self):
  5834. self.ui.grid_gap_x_entry.setText(self.sender().text())
  5835. self.ui.grid_gap_y_entry.setText(self.sender().text())
  5836. def on_grid_add(self):
  5837. # ## Current application units in lower Case
  5838. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5839. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5840. text=_('Enter a Grid Value:'),
  5841. min=0.0000, max=99.9999, decimals=4)
  5842. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  5843. val, ok = grid_add_popup.get_value()
  5844. if ok:
  5845. if float(val) == 0:
  5846. self.inform.emit('[WARNING_NOTCL] %s' %
  5847. _("Please enter a grid value with non-zero value, in Float format."))
  5848. return
  5849. else:
  5850. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5851. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5852. self.inform.emit('[success] %s...' %
  5853. _("New Grid added"))
  5854. else:
  5855. self.inform.emit('[WARNING_NOTCL] %s...' %
  5856. _("Grid already exists"))
  5857. else:
  5858. self.inform.emit('[WARNING_NOTCL] %s...' %
  5859. _("Adding New Grid cancelled"))
  5860. def on_grid_delete(self):
  5861. # ## Current application units in lower Case
  5862. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  5863. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5864. text='Enter a Grid Value:',
  5865. min=0.0000, max=99.9999, decimals=4)
  5866. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  5867. val, ok = grid_del_popup.get_value()
  5868. if ok:
  5869. if float(val) == 0:
  5870. self.inform.emit('[WARNING_NOTCL] %s' %
  5871. _("Please enter a grid value with non-zero value, in Float format."))
  5872. return
  5873. else:
  5874. try:
  5875. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5876. except ValueError:
  5877. self.inform.emit('[ERROR_NOTCL]%s...' %
  5878. _(" Grid Value does not exist"))
  5879. return
  5880. self.inform.emit('[success] %s...' %
  5881. _("Grid Value deleted"))
  5882. else:
  5883. self.inform.emit('[WARNING_NOTCL] %s...' %
  5884. _("Delete Grid value cancelled"))
  5885. def on_shortcut_list(self):
  5886. self.report_usage("on_shortcut_list()")
  5887. # add the tab if it was closed
  5888. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5889. # delete the absolute and relative position and messages in the infobar
  5890. self.ui.position_label.setText("")
  5891. self.ui.rel_position_label.setText("")
  5892. # Switch plot_area to preferences page
  5893. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5894. # self.ui.show()
  5895. def on_select_tab(self, name):
  5896. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5897. if self.ui.splitter.sizes()[0] == 0:
  5898. self.ui.splitter.setSizes([1, 1])
  5899. else:
  5900. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5901. self.ui.splitter.setSizes([0, 1])
  5902. if name == 'project':
  5903. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5904. elif name == 'selected':
  5905. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5906. elif name == 'tool':
  5907. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5908. def on_copy_name(self):
  5909. self.report_usage("on_copy_name()")
  5910. obj = self.collection.get_active()
  5911. try:
  5912. name = obj.options["name"]
  5913. except AttributeError:
  5914. log.debug("on_copy_name() --> No object selected to copy it's name")
  5915. self.inform.emit('[WARNING_NOTCL]%s' %
  5916. _(" No object selected to copy it's name"))
  5917. return
  5918. self.clipboard.setText(name)
  5919. self.inform.emit(_("Name copied on clipboard ..."))
  5920. def on_mouse_click_over_plot(self, event):
  5921. """
  5922. Default actions are:
  5923. :param event: Contains information about the event, like which button
  5924. was clicked, the pixel coordinates and the axes coordinates.
  5925. :return: None
  5926. """
  5927. self.pos = []
  5928. # So it can receive key presses
  5929. self.plotcanvas.native.setFocus()
  5930. # Set the mouse button for panning
  5931. self.plotcanvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  5932. self.pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5933. if self.grid_status() == True:
  5934. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5935. self.app_cursor.enabled = True
  5936. else:
  5937. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5938. self.app_cursor.enabled = False
  5939. try:
  5940. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5941. if event.button == 1:
  5942. # Reset here the relative coordinates so there is a new reference on the click position
  5943. if self.rel_point1 is None:
  5944. self.rel_point1 = self.pos
  5945. else:
  5946. self.rel_point2 = copy(self.rel_point1)
  5947. self.rel_point1 = self.pos
  5948. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5949. if modifiers == QtCore.Qt.ShiftModifier:
  5950. # do not auto open the Project Tab
  5951. self.click_noproject = True
  5952. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  5953. self.inform.emit('[success] %s' %
  5954. _("Coordinates copied to clipboard."))
  5955. return
  5956. self.on_mouse_move_over_plot(event, origin_click=True)
  5957. except Exception as e:
  5958. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5959. def on_double_click_over_plot(self, event):
  5960. self.doubleclick = True
  5961. def on_mouse_move_over_plot(self, event, origin_click=None):
  5962. """
  5963. Callback for the mouse motion event over the plot.
  5964. :param event: Contains information about the event.
  5965. :param origin_click
  5966. :return: None
  5967. """
  5968. # So it can receive key presses
  5969. self.plotcanvas.native.setFocus()
  5970. self.pos_jump = event.pos
  5971. self.ui.popMenu.mouse_is_panning = False
  5972. if not origin_click:
  5973. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5974. if event.button == 2 and event.is_dragging == 1:
  5975. self.ui.popMenu.mouse_is_panning = True
  5976. return
  5977. if self.rel_point1 is not None:
  5978. try: # May fail in case mouse not within axes
  5979. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5980. if self.grid_status() == True:
  5981. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5982. self.app_cursor.enabled = True
  5983. # Update cursor
  5984. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  5985. else:
  5986. pos = (pos_canvas[0], pos_canvas[1])
  5987. self.app_cursor.enabled = False
  5988. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5989. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5990. dx = pos[0] - self.rel_point1[0]
  5991. dy = pos[1] - self.rel_point1[1]
  5992. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5993. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  5994. self.mouse = [pos[0], pos[1]]
  5995. # if the mouse is moved and the LMB is clicked then the action is a selection
  5996. if event.is_dragging == 1 and event.button == 1:
  5997. self.delete_selection_shape()
  5998. if dx < 0:
  5999. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6000. face_color=self.defaults['global_alt_sel_fill'])
  6001. self.selection_type = False
  6002. else:
  6003. self.draw_moving_selection_shape(self.pos, pos)
  6004. self.selection_type = True
  6005. # hover effect - enabled in Preferences -> General -> GUI Settings
  6006. if self.defaults['global_hover']:
  6007. for obj in self.collection.get_list():
  6008. try:
  6009. # select the object(s) only if it is enabled (plotted)
  6010. if obj.options['plot']:
  6011. if obj not in self.collection.get_selected():
  6012. poly_obj = Polygon(
  6013. [(obj.options['xmin'], obj.options['ymin']),
  6014. (obj.options['xmax'], obj.options['ymin']),
  6015. (obj.options['xmax'], obj.options['ymax']),
  6016. (obj.options['xmin'], obj.options['ymax'])]
  6017. )
  6018. if Point(pos).within(poly_obj):
  6019. if obj.isHovering is False:
  6020. obj.isHovering = True
  6021. obj.notHovering = True
  6022. # create the selection box around the selected object
  6023. self.draw_hover_shape(obj, color='#d1e0e0')
  6024. else:
  6025. if obj.notHovering is True:
  6026. obj.notHovering = False
  6027. obj.isHovering = False
  6028. self.delete_hover_shape()
  6029. except:
  6030. # the Exception here will happen if we try to select on screen and we have an
  6031. # newly (and empty) just created Geometry or Excellon object that do not have the
  6032. # xmin, xmax, ymin, ymax options.
  6033. # In this case poly_obj creation (see above) will fail
  6034. pass
  6035. except:
  6036. self.ui.position_label.setText("")
  6037. self.ui.rel_position_label.setText("")
  6038. self.mouse = None
  6039. def on_mouse_click_release_over_plot(self, event):
  6040. """
  6041. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6042. and has been registered in ''self.__init__()''.
  6043. :param event: contains information about the event.
  6044. :return:
  6045. """
  6046. pos = 0, 0
  6047. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  6048. if self.grid_status() == True:
  6049. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6050. else:
  6051. pos = (pos_canvas[0], pos_canvas[1])
  6052. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6053. # canvas menu
  6054. if event.button == 2: # right click
  6055. if self.ui.popMenu.mouse_is_panning is False:
  6056. self.cursor = QtGui.QCursor()
  6057. self.populate_cmenu_grids()
  6058. self.ui.popMenu.popup(self.cursor.pos())
  6059. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6060. # selection and then select a type of selection ("enclosing" or "touching")
  6061. try:
  6062. if event.button == 1: # left click
  6063. if self.doubleclick is True:
  6064. self.doubleclick = False
  6065. if self.collection.get_selected():
  6066. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6067. if self.ui.splitter.sizes()[0] == 0:
  6068. self.ui.splitter.setSizes([1, 1])
  6069. # delete the selection shape(S) as it may be in the way
  6070. self.delete_selection_shape()
  6071. self.delete_hover_shape()
  6072. else:
  6073. if self.selection_type is not None:
  6074. self.selection_area_handler(self.pos, pos, self.selection_type)
  6075. self.selection_type = None
  6076. else:
  6077. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6078. if key_modifier == QtCore.Qt.ShiftModifier:
  6079. mod_key = 'Shift'
  6080. elif key_modifier == QtCore.Qt.ControlModifier:
  6081. mod_key = 'Control'
  6082. else:
  6083. mod_key = None
  6084. if mod_key == self.defaults["global_mselect_key"]:
  6085. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6086. # deselect, and if it's not selected then it will be selected
  6087. # If there is no active command (self.command_active is None) then we check if we clicked
  6088. # on a object by checking the bounding limits against mouse click position
  6089. if self.command_active is None:
  6090. self.select_objects(key='CTRL')
  6091. self.delete_hover_shape()
  6092. else:
  6093. # If there is no active command (self.command_active is None) then we check if we clicked
  6094. # on a object by checking the bounding limits against mouse click position
  6095. if self.command_active is None:
  6096. self.select_objects()
  6097. self.delete_hover_shape()
  6098. except Exception as e:
  6099. log.warning("Error: %s" % str(e))
  6100. return
  6101. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6102. """
  6103. :param start_pos: mouse position when the selection LMB click was done
  6104. :param end_pos: mouse position when the left mouse button is released
  6105. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6106. :return:
  6107. """
  6108. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6109. self.delete_selection_shape()
  6110. for obj in self.collection.get_list():
  6111. try:
  6112. # select the object(s) only if it is enabled (plotted)
  6113. if obj.options['plot']:
  6114. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6115. (obj.options['xmax'], obj.options['ymin']),
  6116. (obj.options['xmax'], obj.options['ymax']),
  6117. (obj.options['xmin'], obj.options['ymax'])])
  6118. if sel_type is True:
  6119. if poly_obj.within(poly_selection):
  6120. # create the selection box around the selected object
  6121. if self.defaults['global_selection_shape'] is True:
  6122. self.draw_selection_shape(obj)
  6123. self.collection.set_active(obj.options['name'])
  6124. else:
  6125. if poly_selection.intersects(poly_obj):
  6126. # create the selection box around the selected object
  6127. if self.defaults['global_selection_shape'] is True:
  6128. self.draw_selection_shape(obj)
  6129. self.collection.set_active(obj.options['name'])
  6130. except Exception as e:
  6131. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6132. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6133. # In this case poly_obj creation (see above) will fail
  6134. log.debug("App.selection_area_handler() --> %s" % str(e))
  6135. def select_objects(self, key=None):
  6136. # list where we store the overlapped objects under our mouse left click position
  6137. objects_under_the_click_list = []
  6138. # Populate the list with the overlapped objects on the click position
  6139. curr_x, curr_y = self.pos
  6140. for obj in self.all_objects_list:
  6141. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6142. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6143. if obj.options['name'] not in objects_under_the_click_list:
  6144. if obj.options['plot']:
  6145. # add objects to the objects_under_the_click list only if the object is plotted
  6146. # (active and not disabled)
  6147. objects_under_the_click_list.append(obj.options['name'])
  6148. try:
  6149. # If there is no element in the overlapped objects list then make everyone inactive
  6150. # because we selected "nothing"
  6151. if not objects_under_the_click_list:
  6152. self.collection.set_all_inactive()
  6153. # delete the possible selection box around a possible selected object
  6154. self.delete_selection_shape()
  6155. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6156. # only when working on App
  6157. if self.call_source == 'app':
  6158. if self.click_noproject is False:
  6159. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6160. else:
  6161. # restore auto open the Project Tab
  6162. self.click_noproject = False
  6163. # delete any text in the status bar, implicitly the last object name that was selected
  6164. self.inform.emit("")
  6165. else:
  6166. self.call_source = 'app'
  6167. else:
  6168. # case when there is only an object under the click and we toggle it
  6169. if len(objects_under_the_click_list) == 1:
  6170. if self.collection.get_active() is None:
  6171. self.collection.set_active(objects_under_the_click_list[0])
  6172. # create the selection box around the selected object
  6173. curr_sel_obj = self.collection.get_active()
  6174. if self.defaults['global_selection_shape'] is True:
  6175. self.draw_selection_shape(curr_sel_obj)
  6176. # self.inform.emit('[selected] %s: %s selected' %
  6177. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6178. if curr_sel_obj.kind == 'gerber':
  6179. self.inform.emit(
  6180. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6181. color='green', name=str(curr_sel_obj.options['name'])))
  6182. elif curr_sel_obj.kind == 'excellon':
  6183. self.inform.emit(
  6184. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6185. color='brown', name=str(curr_sel_obj.options['name'])))
  6186. elif curr_sel_obj.kind == 'cncjob':
  6187. self.inform.emit(
  6188. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6189. color='blue', name=str(curr_sel_obj.options['name'])))
  6190. elif curr_sel_obj.kind == 'geometry':
  6191. self.inform.emit(
  6192. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6193. color='red', name=str(curr_sel_obj.options['name'])))
  6194. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6195. self.collection.set_all_inactive()
  6196. self.delete_selection_shape()
  6197. self.collection.set_active(objects_under_the_click_list[0])
  6198. # create the selection box around the selected object
  6199. curr_sel_obj = self.collection.get_active()
  6200. if self.defaults['global_selection_shape'] is True:
  6201. self.draw_selection_shape(curr_sel_obj)
  6202. # self.inform.emit('[selected] %s: %s selected' %
  6203. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6204. if curr_sel_obj.kind == 'gerber':
  6205. self.inform.emit(
  6206. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6207. color='green', name=str(curr_sel_obj.options['name'])))
  6208. elif curr_sel_obj.kind == 'excellon':
  6209. self.inform.emit(
  6210. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6211. color='brown', name=str(curr_sel_obj.options['name'])))
  6212. elif curr_sel_obj.kind == 'cncjob':
  6213. self.inform.emit(
  6214. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6215. color='blue', name=str(curr_sel_obj.options['name'])))
  6216. elif curr_sel_obj.kind == 'geometry':
  6217. self.inform.emit(
  6218. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6219. color='red', name=str(curr_sel_obj.options['name'])))
  6220. else:
  6221. self.collection.set_all_inactive()
  6222. self.delete_selection_shape()
  6223. if self.call_source == 'app':
  6224. # delete any text in the status bar, implicitly the last object name that was selected
  6225. self.inform.emit("")
  6226. else:
  6227. self.call_source = 'app'
  6228. else:
  6229. # If there is no selected object
  6230. # make active the first element of the overlapped objects list
  6231. if self.collection.get_active() is None:
  6232. self.collection.set_active(objects_under_the_click_list[0])
  6233. name_sel_obj = self.collection.get_active().options['name']
  6234. # In case that there is a selected object but it is not in the overlapped object list
  6235. # make that object inactive and activate the first element in the overlapped object list
  6236. if name_sel_obj not in objects_under_the_click_list:
  6237. self.collection.set_inactive(name_sel_obj)
  6238. name_sel_obj = objects_under_the_click_list[0]
  6239. self.collection.set_active(name_sel_obj)
  6240. else:
  6241. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6242. self.collection.set_all_inactive()
  6243. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6244. len(objects_under_the_click_list)])
  6245. curr_sel_obj = self.collection.get_active()
  6246. # delete the possible selection box around a possible selected object
  6247. self.delete_selection_shape()
  6248. # create the selection box around the selected object
  6249. if self.defaults['global_selection_shape'] is True:
  6250. self.draw_selection_shape(curr_sel_obj)
  6251. # self.inform.emit('[selected] %s: %s selected' %
  6252. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6253. if curr_sel_obj.kind == 'gerber':
  6254. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6255. color='green', name=str(curr_sel_obj.options['name'])))
  6256. elif curr_sel_obj.kind == 'excellon':
  6257. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6258. color='brown', name=str(curr_sel_obj.options['name'])))
  6259. elif curr_sel_obj.kind == 'cncjob':
  6260. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6261. color='blue', name=str(curr_sel_obj.options['name'])))
  6262. elif curr_sel_obj.kind == 'geometry':
  6263. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6264. color='red', name=str(curr_sel_obj.options['name'])))
  6265. # for obj in self.collection.get_list():
  6266. # obj.plot()
  6267. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6268. # TODO: on selected objects change the object colors and do not draw the selection box
  6269. # self.plotcanvas.update() # this updates the canvas
  6270. except Exception as e:
  6271. log.error("[ERROR] Something went bad. %s" % str(e))
  6272. return
  6273. def delete_hover_shape(self):
  6274. self.hover_shapes.clear()
  6275. self.hover_shapes.redraw()
  6276. def draw_hover_shape(self, sel_obj, color=None):
  6277. """
  6278. :param sel_obj: the object for which the hover shape must be drawn
  6279. :return:
  6280. """
  6281. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6282. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6283. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6284. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6285. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6286. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6287. hover_rect = hover_rect.buffer(-0.1)
  6288. hover_rect = hover_rect.buffer(0.2)
  6289. else:
  6290. hover_rect = hover_rect.buffer(-0.00393)
  6291. hover_rect = hover_rect.buffer(0.00787)
  6292. if color:
  6293. face = Color(color)
  6294. face.alpha = 0.2
  6295. outline = Color(color, alpha=0.8)
  6296. else:
  6297. face = Color(self.defaults['global_sel_fill'])
  6298. face.alpha = 0.2
  6299. outline = self.defaults['global_sel_line']
  6300. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  6301. def delete_selection_shape(self):
  6302. self.move_tool.sel_shapes.clear()
  6303. self.move_tool.sel_shapes.redraw()
  6304. def draw_selection_shape(self, sel_obj, color=None):
  6305. """
  6306. :param sel_obj: the object for which the selection shape must be drawn
  6307. :return:
  6308. """
  6309. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6310. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6311. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6312. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6313. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6314. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6315. sel_rect = sel_rect.buffer(-0.1)
  6316. sel_rect = sel_rect.buffer(0.2)
  6317. else:
  6318. sel_rect = sel_rect.buffer(-0.00393)
  6319. sel_rect = sel_rect.buffer(0.00787)
  6320. if color:
  6321. face = Color(color, alpha=0.2)
  6322. outline = Color(color, alpha=0.8)
  6323. else:
  6324. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  6325. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  6326. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6327. color=outline,
  6328. face_color=face,
  6329. update=True,
  6330. layer=0,
  6331. tolerance=None))
  6332. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6333. """
  6334. :param old_coords: old coordinates
  6335. :param coords: new coordinates
  6336. :return:
  6337. """
  6338. if 'color' in kwargs:
  6339. color = kwargs['color']
  6340. else:
  6341. color = self.defaults['global_sel_line']
  6342. if 'face_color' in kwargs:
  6343. face_color = kwargs['face_color']
  6344. else:
  6345. face_color = self.defaults['global_sel_fill']
  6346. if 'face_alpha' in kwargs:
  6347. face_alpha = kwargs['face_alpha']
  6348. else:
  6349. face_alpha = 0.3
  6350. x0, y0 = old_coords
  6351. x1, y1 = coords
  6352. pt1 = (x0, y0)
  6353. pt2 = (x1, y0)
  6354. pt3 = (x1, y1)
  6355. pt4 = (x0, y1)
  6356. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6357. color_t = Color(face_color)
  6358. color_t.alpha = face_alpha
  6359. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6360. layer=0, tolerance=None)
  6361. def on_file_new_click(self):
  6362. if self.collection.get_list() and self.should_we_save:
  6363. msgbox = QtWidgets.QMessageBox()
  6364. # msgbox.setText("<B>Save changes ...</B>")
  6365. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6366. "Creating a New project will delete them.\n"
  6367. "Do you want to Save the project?"))
  6368. msgbox.setWindowTitle(_("Save changes"))
  6369. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6370. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6371. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6372. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6373. msgbox.setDefaultButton(bt_yes)
  6374. msgbox.exec_()
  6375. response = msgbox.clickedButton()
  6376. if response == bt_yes:
  6377. self.on_file_saveprojectas()
  6378. elif response == bt_cancel:
  6379. return
  6380. elif response == bt_no:
  6381. self.on_file_new()
  6382. else:
  6383. self.on_file_new()
  6384. self.inform.emit('[success] %s...' %
  6385. _("New Project created"))
  6386. def on_file_new(self, cli=None):
  6387. """
  6388. Callback for menu item File->New. Returns the application to its
  6389. startup state. This method is thread-safe.
  6390. :return: None
  6391. """
  6392. self.report_usage("on_file_new")
  6393. # Remove everything from memory
  6394. App.log.debug("on_file_new()")
  6395. if self.call_source != 'app':
  6396. self.editor2object(cleanup=True)
  6397. # ## EDITOR section
  6398. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  6399. self.exc_editor = FlatCAMExcEditor(self)
  6400. self.grb_editor = FlatCAMGrbEditor(self)
  6401. # Clear pool
  6402. self.clear_pool()
  6403. for obj in self.collection.get_list():
  6404. # delete shapes left drawn from mark shape_collections, if any
  6405. if isinstance(obj, FlatCAMGerber):
  6406. try:
  6407. obj.mark_shapes.enabled = False
  6408. obj.mark_shapes.clear(update=True)
  6409. except AttributeError:
  6410. pass
  6411. # also delete annotation shapes, if any
  6412. elif isinstance(obj, FlatCAMCNCjob):
  6413. try:
  6414. obj.annotation.enabled = False
  6415. obj.annotation.clear(update=True)
  6416. except AttributeError:
  6417. pass
  6418. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6419. self.init_tcl()
  6420. self.delete_selection_shape()
  6421. self.collection.delete_all()
  6422. self.setup_component_editor()
  6423. # Clear project filename
  6424. self.project_filename = None
  6425. # Load the application defaults
  6426. self.load_defaults(filename='current_defaults')
  6427. # Re-fresh project options
  6428. self.on_options_app2project()
  6429. # Init Tools
  6430. self.init_tools()
  6431. if cli is None:
  6432. # Close any Tabs opened in the Plot Tab Area section
  6433. for index in range(self.ui.plot_tab_area.count()):
  6434. self.ui.plot_tab_area.closeTab(index)
  6435. # for whatever reason previous command does not close the last tab so I do it manually
  6436. self.ui.plot_tab_area.closeTab(0)
  6437. # # And then add again the Plot Area
  6438. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6439. self.ui.plot_tab_area.protectTab(0)
  6440. # take the focus of the Notebook on Project Tab.
  6441. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6442. self.set_ui_title(name=_("New Project - Not saved"))
  6443. def obj_properties(self):
  6444. self.report_usage("obj_properties()")
  6445. self.properties_tool.run(toggle=False)
  6446. def on_project_context_save(self):
  6447. obj = self.collection.get_active()
  6448. if type(obj) == FlatCAMGeometry:
  6449. self.on_file_exportdxf()
  6450. elif type(obj) == FlatCAMExcellon:
  6451. self.on_file_saveexcellon()
  6452. elif type(obj) == FlatCAMCNCjob:
  6453. obj.on_exportgcode_button_click()
  6454. elif type(obj) == FlatCAMGerber:
  6455. self.on_file_savegerber()
  6456. def obj_move(self):
  6457. self.report_usage("obj_move()")
  6458. self.move_tool.run(toggle=False)
  6459. def on_fileopengerber(self, checked=None, name=None):
  6460. """
  6461. File menu callback for opening a Gerber.
  6462. :return: None
  6463. """
  6464. self.report_usage("on_fileopengerber")
  6465. App.log.debug("on_fileopengerber()")
  6466. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6467. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6468. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  6469. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6470. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6471. "*.mil);;" \
  6472. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6473. "Allegro Files (*.art);;" \
  6474. "Mentor Files (*.pho *.gdo);;" \
  6475. "All Files (*.*)"
  6476. if name is None:
  6477. try:
  6478. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6479. directory=self.get_last_folder(),
  6480. filter=_filter_)
  6481. except TypeError:
  6482. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6483. filenames = [str(filename) for filename in filenames]
  6484. else:
  6485. filenames = [name]
  6486. if len(filenames) == 0:
  6487. self.inform.emit('[WARNING_NOTCL] %s' %
  6488. _("Open Gerber cancelled."))
  6489. else:
  6490. for filename in filenames:
  6491. if filename != '':
  6492. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6493. def on_fileopenexcellon(self, checked=None, name=None):
  6494. """
  6495. File menu callback for opening an Excellon file.
  6496. :return: None
  6497. """
  6498. self.report_usage("on_fileopenexcellon")
  6499. App.log.debug("on_fileopenexcellon()")
  6500. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6501. "All Files (*.*)"
  6502. if name is None:
  6503. try:
  6504. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6505. directory=self.get_last_folder(),
  6506. filter=_filter_)
  6507. except TypeError:
  6508. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6509. filenames = [str(filename) for filename in filenames]
  6510. else:
  6511. filenames = [str(name)]
  6512. if len(filenames) == 0:
  6513. self.inform.emit('[WARNING_NOTCL]%s' %
  6514. _(" Open Excellon cancelled."))
  6515. else:
  6516. for filename in filenames:
  6517. if filename != '':
  6518. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6519. def on_fileopengcode(self, checked=None, name=None):
  6520. """
  6521. File menu call back for opening gcode.
  6522. :return: None
  6523. """
  6524. self.report_usage("on_fileopengcode")
  6525. App.log.debug("on_fileopengcode()")
  6526. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6527. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6528. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  6529. "All Files (*.*)"
  6530. if name is None:
  6531. try:
  6532. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6533. directory=self.get_last_folder(),
  6534. filter=_filter_)
  6535. except TypeError:
  6536. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6537. filenames = [str(filename) for filename in filenames]
  6538. else:
  6539. filenames = [name]
  6540. if len(filenames) == 0:
  6541. self.inform.emit('[WARNING_NOTCL] %s' %
  6542. _("Open G-Code cancelled."))
  6543. else:
  6544. for filename in filenames:
  6545. if filename != '':
  6546. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  6547. def on_file_openproject(self, checked=None):
  6548. """
  6549. File menu callback for opening a project.
  6550. :return: None
  6551. """
  6552. self.report_usage("on_file_openproject")
  6553. App.log.debug("on_file_openproject()")
  6554. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6555. try:
  6556. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6557. directory=self.get_last_folder(), filter=_filter_)
  6558. except TypeError:
  6559. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6560. # The Qt methods above will return a QString which can cause problems later.
  6561. # So far json.dump() will fail to serialize it.
  6562. # TODO: Improve the serialization methods and remove this fix.
  6563. filename = str(filename)
  6564. if filename == "":
  6565. self.inform.emit('[WARNING_NOTCL] %s' %
  6566. _("Open Project cancelled."))
  6567. else:
  6568. # self.worker_task.emit({'fcn': self.open_project,
  6569. # 'params': [filename]})
  6570. # The above was failing because open_project() is not
  6571. # thread safe. The new_project()
  6572. self.open_project(filename)
  6573. def on_file_openconfig(self, checked=None):
  6574. """
  6575. File menu callback for opening a config file.
  6576. :return: None
  6577. """
  6578. self.report_usage("on_file_openconfig")
  6579. App.log.debug("on_file_openconfig()")
  6580. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6581. try:
  6582. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6583. directory=self.data_path, filter=_filter_)
  6584. except TypeError:
  6585. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6586. filter=_filter_)
  6587. if filename == "":
  6588. self.inform.emit('[WARNING_NOTCL] %s' %
  6589. _("Open Config cancelled."))
  6590. else:
  6591. self.open_config_file(filename)
  6592. def on_file_exportsvg(self):
  6593. """
  6594. Callback for menu item File->Export SVG.
  6595. :return: None
  6596. """
  6597. self.report_usage("on_file_exportsvg")
  6598. App.log.debug("on_file_exportsvg()")
  6599. obj = self.collection.get_active()
  6600. if obj is None:
  6601. self.inform.emit('[WARNING_NOTCL] %s' %
  6602. _("No object selected."))
  6603. msg = _("Please Select a Geometry object to export")
  6604. msgbox = QtWidgets.QMessageBox()
  6605. msgbox.setInformativeText(msg)
  6606. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6607. msgbox.setDefaultButton(bt_ok)
  6608. msgbox.exec_()
  6609. return
  6610. # Check for more compatible types and add as required
  6611. if (not isinstance(obj, FlatCAMGeometry)
  6612. and not isinstance(obj, FlatCAMGerber)
  6613. and not isinstance(obj, FlatCAMCNCjob)
  6614. and not isinstance(obj, FlatCAMExcellon)):
  6615. msg = '[ERROR_NOTCL] %s' % \
  6616. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6617. msgbox = QtWidgets.QMessageBox()
  6618. msgbox.setInformativeText(msg)
  6619. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6620. msgbox.setDefaultButton(bt_ok)
  6621. msgbox.exec_()
  6622. return
  6623. name = obj.options["name"]
  6624. _filter = "SVG File (*.svg);;All Files (*.*)"
  6625. try:
  6626. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6627. caption=_("Export SVG"),
  6628. directory=self.get_last_save_folder() + '/' + str(name),
  6629. filter=_filter)
  6630. except TypeError:
  6631. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  6632. filename = str(filename)
  6633. if filename == "":
  6634. self.inform.emit('[WARNING_NOTCL]%s' %
  6635. _(" Export SVG cancelled."))
  6636. return
  6637. else:
  6638. self.export_svg(name, filename)
  6639. if self.defaults["global_open_style"] is False:
  6640. self.file_opened.emit("SVG", filename)
  6641. self.file_saved.emit("SVG", filename)
  6642. def on_file_exportpng(self):
  6643. self.report_usage("on_file_exportpng")
  6644. App.log.debug("on_file_exportpng()")
  6645. self.date = str(datetime.today()).rpartition('.')[0]
  6646. self.date = ''.join(c for c in self.date if c not in ':-')
  6647. self.date = self.date.replace(' ', '_')
  6648. image = _screenshot()
  6649. data = np.asarray(image)
  6650. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6651. self.inform.emit('[[WARNING_NOTCL]] %s' %
  6652. _('Data must be a 3D array with last dimension 3 or 4'))
  6653. return
  6654. filter_ = "PNG File (*.png);;All Files (*.*)"
  6655. try:
  6656. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6657. caption=_("Export PNG Image"),
  6658. directory=self.get_last_save_folder() + '/png_' + self.date,
  6659. filter=filter_)
  6660. except TypeError:
  6661. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  6662. filename = str(filename)
  6663. if filename == "":
  6664. self.inform.emit(_("Export PNG cancelled."))
  6665. return
  6666. else:
  6667. write_png(filename, data)
  6668. if self.defaults["global_open_style"] is False:
  6669. self.file_opened.emit("png", filename)
  6670. self.file_saved.emit("png", filename)
  6671. def on_file_savegerber(self):
  6672. """
  6673. Callback for menu item in Project context menu.
  6674. :return: None
  6675. """
  6676. self.report_usage("on_file_savegerber")
  6677. App.log.debug("on_file_savegerber()")
  6678. obj = self.collection.get_active()
  6679. if obj is None:
  6680. self.inform.emit('[WARNING_NOTCL] %s' %
  6681. _("No object selected. Please select an Gerber object to export."))
  6682. return
  6683. # Check for more compatible types and add as required
  6684. if not isinstance(obj, FlatCAMGerber):
  6685. self.inform.emit('[ERROR_NOTCL] %s' %
  6686. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6687. return
  6688. name = self.collection.get_active().options["name"]
  6689. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6690. try:
  6691. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6692. caption="Save Gerber source file",
  6693. directory=self.get_last_save_folder() + '/' + name,
  6694. filter=_filter)
  6695. except TypeError:
  6696. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  6697. filename = str(filename)
  6698. if filename == "":
  6699. self.inform.emit('[WARNING_NOTCL] %s' %
  6700. _("Save Gerber source file cancelled."))
  6701. return
  6702. else:
  6703. self.save_source_file(name, filename)
  6704. if self.defaults["global_open_style"] is False:
  6705. self.file_opened.emit("Gerber", filename)
  6706. self.file_saved.emit("Gerber", filename)
  6707. def on_file_saveexcellon(self):
  6708. """
  6709. Callback for menu item in project context menu.
  6710. :return: None
  6711. """
  6712. self.report_usage("on_file_saveexcellon")
  6713. App.log.debug("on_file_saveexcellon()")
  6714. obj = self.collection.get_active()
  6715. if obj is None:
  6716. self.inform.emit('[WARNING_NOTCL] %s' %
  6717. _("No object selected. Please select an Excellon object to export."))
  6718. return
  6719. # Check for more compatible types and add as required
  6720. if not isinstance(obj, FlatCAMExcellon):
  6721. self.inform.emit('[ERROR_NOTCL] %s' %
  6722. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6723. return
  6724. name = self.collection.get_active().options["name"]
  6725. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6726. try:
  6727. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6728. caption=_("Save Excellon source file"),
  6729. directory=self.get_last_save_folder() + '/' + name,
  6730. filter=_filter)
  6731. except TypeError:
  6732. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  6733. filename = str(filename)
  6734. if filename == "":
  6735. self.inform.emit('[WARNING_NOTCL] %s' %
  6736. _("Saving Excellon source file cancelled."))
  6737. return
  6738. else:
  6739. self.save_source_file(name, filename)
  6740. if self.defaults["global_open_style"] is False:
  6741. self.file_opened.emit("Excellon", filename)
  6742. self.file_saved.emit("Excellon", filename)
  6743. def on_file_exportexcellon(self):
  6744. """
  6745. Callback for menu item File->Export->Excellon.
  6746. :return: None
  6747. """
  6748. self.report_usage("on_file_exportexcellon")
  6749. App.log.debug("on_file_exportexcellon()")
  6750. obj = self.collection.get_active()
  6751. if obj is None:
  6752. self.inform.emit('[WARNING_NOTCL] %s' %
  6753. _("No object selected. Please Select an Excellon object to export."))
  6754. return
  6755. # Check for more compatible types and add as required
  6756. if not isinstance(obj, FlatCAMExcellon):
  6757. self.inform.emit('[ERROR_NOTCL] %s' %
  6758. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6759. return
  6760. name = self.collection.get_active().options["name"]
  6761. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6762. try:
  6763. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6764. caption=_("Export Excellon"),
  6765. directory=self.get_last_save_folder() + '/' + name,
  6766. filter=_filter)
  6767. except TypeError:
  6768. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  6769. filename = str(filename)
  6770. if filename == "":
  6771. self.inform.emit('[WARNING_NOTCL] %s' %
  6772. _("Export Excellon cancelled."))
  6773. return
  6774. else:
  6775. self.export_excellon(name, filename)
  6776. if self.defaults["global_open_style"] is False:
  6777. self.file_opened.emit("Excellon", filename)
  6778. self.file_saved.emit("Excellon", filename)
  6779. def on_file_exportgerber(self):
  6780. """
  6781. Callback for menu item File->Export->Gerber.
  6782. :return: None
  6783. """
  6784. self.report_usage("on_file_exportgerber")
  6785. App.log.debug("on_file_exportgerber()")
  6786. obj = self.collection.get_active()
  6787. if obj is None:
  6788. self.inform.emit('[WARNING_NOTCL] %s' %
  6789. _("No object selected. Please Select an Gerber object to export."))
  6790. return
  6791. # Check for more compatible types and add as required
  6792. if not isinstance(obj, FlatCAMGerber):
  6793. self.inform.emit('[ERROR_NOTCL] %s' %
  6794. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6795. return
  6796. name = self.collection.get_active().options["name"]
  6797. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  6798. try:
  6799. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6800. caption=_("Export Gerber"),
  6801. directory=self.get_last_save_folder() + '/' + name,
  6802. filter=_filter_)
  6803. except TypeError:
  6804. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  6805. filename = str(filename)
  6806. if filename == "":
  6807. self.inform.emit('[WARNING_NOTCL] %s' %
  6808. _("Export Gerber cancelled."))
  6809. return
  6810. else:
  6811. self.export_gerber(name, filename)
  6812. if self.defaults["global_open_style"] is False:
  6813. self.file_opened.emit("Gerber", filename)
  6814. self.file_saved.emit("Gerber", filename)
  6815. def on_file_exportdxf(self):
  6816. """
  6817. Callback for menu item File->Export DXF.
  6818. :return: None
  6819. """
  6820. self.report_usage("on_file_exportdxf")
  6821. App.log.debug("on_file_exportdxf()")
  6822. obj = self.collection.get_active()
  6823. if obj is None:
  6824. self.inform.emit('[WARNING_NOTCL] %s' %
  6825. _("No object selected."))
  6826. msg = _("Please Select a Geometry object to export")
  6827. msgbox = QtWidgets.QMessageBox()
  6828. msgbox.setInformativeText(msg)
  6829. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6830. msgbox.setDefaultButton(bt_ok)
  6831. msgbox.exec_()
  6832. return
  6833. # Check for more compatible types and add as required
  6834. if not isinstance(obj, FlatCAMGeometry):
  6835. msg = '[ERROR_NOTCL] %s' % \
  6836. _("Only Geometry objects can be used.")
  6837. msgbox = QtWidgets.QMessageBox()
  6838. msgbox.setInformativeText(msg)
  6839. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6840. msgbox.setDefaultButton(bt_ok)
  6841. msgbox.exec_()
  6842. return
  6843. name = self.collection.get_active().options["name"]
  6844. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  6845. try:
  6846. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  6847. caption=_("Export DXF"),
  6848. directory=self.get_last_save_folder() + '/' + name,
  6849. filter=_filter_)
  6850. except TypeError:
  6851. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  6852. filter=_filter_)
  6853. filename = str(filename)
  6854. if filename == "":
  6855. self.inform.emit('[WARNING_NOTCL] %s' %
  6856. _("Export DXF cancelled."))
  6857. return
  6858. else:
  6859. self.export_dxf(name, filename)
  6860. if self.defaults["global_open_style"] is False:
  6861. self.file_opened.emit("DXF", filename)
  6862. self.file_saved.emit("DXF", filename)
  6863. def on_file_importsvg(self, type_of_obj):
  6864. """
  6865. Callback for menu item File->Import SVG.
  6866. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6867. :type type_of_obj: str
  6868. :return: None
  6869. """
  6870. self.report_usage("on_file_importsvg")
  6871. App.log.debug("on_file_importsvg()")
  6872. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  6873. try:
  6874. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6875. directory=self.get_last_folder(), filter=_filter_)
  6876. except TypeError:
  6877. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6878. filter=_filter_)
  6879. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  6880. type_of_obj = "geometry"
  6881. filenames = [str(filename) for filename in filenames]
  6882. if len(filenames) == 0:
  6883. self.inform.emit('[WARNING_NOTCL] %s' %
  6884. _("Open SVG cancelled."))
  6885. else:
  6886. for filename in filenames:
  6887. if filename != '':
  6888. self.worker_task.emit({'fcn': self.import_svg,
  6889. 'params': [filename, type_of_obj]})
  6890. def on_file_importdxf(self, type_of_obj):
  6891. """
  6892. Callback for menu item File->Import DXF.
  6893. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6894. :type type_of_obj: str
  6895. :return: None
  6896. """
  6897. self.report_usage("on_file_importdxf")
  6898. App.log.debug("on_file_importdxf()")
  6899. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  6900. try:
  6901. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6902. directory=self.get_last_folder(),
  6903. filter=_filter_)
  6904. except TypeError:
  6905. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6906. filter=_filter_)
  6907. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  6908. type_of_obj = "geometry"
  6909. filenames = [str(filename) for filename in filenames]
  6910. if len(filenames) == 0:
  6911. self.inform.emit('[WARNING_NOTCL] %s' %
  6912. _("Open DXF cancelled."))
  6913. else:
  6914. for filename in filenames:
  6915. if filename != '':
  6916. self.worker_task.emit({'fcn': self.import_dxf,
  6917. 'params': [filename, type_of_obj]})
  6918. # ###############################################################################################################
  6919. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6920. # ###############################################################################################################
  6921. def init_code_editor(self, name):
  6922. # Signals section
  6923. # Disconnect the old signals
  6924. try:
  6925. self.ui.buttonOpen.clicked.disconnect()
  6926. except TypeError:
  6927. pass
  6928. try:
  6929. self.ui.buttonSave.clicked.disconnect()
  6930. except TypeError:
  6931. pass
  6932. # add the tab if it was closed
  6933. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, '%s' % name)
  6934. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  6935. # delete the absolute and relative position and messages in the infobar
  6936. self.ui.position_label.setText("")
  6937. self.ui.rel_position_label.setText("")
  6938. # first clear previous text in text editor (if any)
  6939. self.ui.code_editor.clear()
  6940. self.ui.code_editor.setReadOnly(False)
  6941. self.toggle_codeeditor = True
  6942. self.ui.code_editor.completer_enable = False
  6943. self.ui.buttonRun.hide()
  6944. # make sure to keep a reference to the code editor
  6945. self.reference_code_editor = self.ui.code_editor
  6946. # Switch plot_area to CNCJob tab
  6947. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  6948. def on_view_source(self):
  6949. self.inform.emit('%s' %
  6950. _("Viewing the source code of the selected object."))
  6951. self.proc_container.view.set_busy(_("Loading..."))
  6952. try:
  6953. obj = self.collection.get_active()
  6954. except Exception as e:
  6955. log.debug("App.on_view_source() --> %s" % str(e))
  6956. self.inform.emit('[WARNING_NOTCL] %s' %
  6957. _("Select an Gerber or Excellon file to view it's source file."))
  6958. return 'fail'
  6959. if obj.kind == 'gerber':
  6960. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  6961. elif obj.kind == 'excellon':
  6962. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  6963. elif obj.kind == 'cncjob':
  6964. "GCode Files (*.NC);;All Files (*.*)"
  6965. else:
  6966. flt = "All Files (*.*)"
  6967. self.init_code_editor(name=_("Source Editor"))
  6968. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  6969. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  6970. # then append the text from GCode to the text editor
  6971. if obj.kind == 'cncjob':
  6972. try:
  6973. file = obj.export_gcode(
  6974. preamble=self.defaults["cncjob_prepend"],
  6975. postamble=self.defaults["cncjob_append"],
  6976. to_file=True)
  6977. if file == 'fail':
  6978. return 'fail'
  6979. except AttributeError:
  6980. self.inform.emit('[WARNING_NOTCL] %s' %
  6981. _("There is no selected object for which to see it's source file code."))
  6982. return 'fail'
  6983. else:
  6984. try:
  6985. file = StringIO(obj.source_file)
  6986. except AttributeError:
  6987. self.inform.emit('[WARNING_NOTCL] %s' %
  6988. _("There is no selected object for which to see it's source file code."))
  6989. return 'fail'
  6990. self.ui.cncjob_frame.hide()
  6991. try:
  6992. for line in file:
  6993. QtWidgets.QApplication.processEvents()
  6994. proc_line = str(line).strip('\n')
  6995. self.ui.code_editor.append(proc_line)
  6996. except Exception as e:
  6997. log.debug('App.on_view_source() -->%s' % str(e))
  6998. self.inform.emit('[ERROR] %s: %s' %
  6999. (_('Failed to load the source code for the selected object'), str(e)))
  7000. return
  7001. self.handleTextChanged()
  7002. self.ui.cncjob_frame.show()
  7003. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7004. self.proc_container.view.set_idle()
  7005. # self.ui.show()
  7006. def on_toggle_code_editor(self):
  7007. self.report_usage("on_toggle_code_editor()")
  7008. if self.toggle_codeeditor is False:
  7009. self.init_code_editor(name=_("Code Editor"))
  7010. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  7011. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  7012. else:
  7013. for idx in range(self.ui.plot_tab_area.count()):
  7014. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  7015. self.ui.plot_tab_area.closeTab(idx)
  7016. break
  7017. self.toggle_codeeditor = False
  7018. def on_filenewscript(self):
  7019. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7020. self.init_code_editor(name=_("Script Editor"))
  7021. self.ui.code_editor.completer_enable = True
  7022. self.ui.code_editor.append(_(
  7023. "#\n"
  7024. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  7025. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  7026. "#\n\n"
  7027. "# FlatCAM commands list:\n"
  7028. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, ClearCopper,\n"
  7029. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames,\n"
  7030. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  7031. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  7032. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,\n"
  7033. "# SubtractRectangle, Version, WriteGCode\n"
  7034. "#\n\n"
  7035. ))
  7036. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7037. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7038. self.ui.buttonRun.show()
  7039. try:
  7040. self.ui.buttonRun.clicked.disconnect(self.handleRunCode)
  7041. except TypeError:
  7042. pass
  7043. self.ui.buttonRun.clicked.connect(self.handleRunCode)
  7044. self.handleTextChanged()
  7045. self.ui.code_editor.show()
  7046. def on_fileopenscript(self):
  7047. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7048. try:
  7049. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  7050. directory=self.get_last_folder(), filter=_filter_)
  7051. except TypeError:
  7052. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  7053. # The Qt methods above will return a QString which can cause problems later.
  7054. # So far json.dump() will fail to serialize it.
  7055. # TODO: Improve the serialization methods and remove this fix.
  7056. filename = str(filename)
  7057. if filename == "":
  7058. self.inform.emit('[WARNING_NOTCL] %s' %
  7059. _("Open TCL script cancelled."))
  7060. else:
  7061. self.on_filenewscript()
  7062. try:
  7063. with open(filename, "r") as opened_script:
  7064. try:
  7065. for line in opened_script:
  7066. proc_line = str(line).strip('\n')
  7067. self.ui.code_editor.append(proc_line)
  7068. except Exception as e:
  7069. log.debug('App.on_fileopenscript() -->%s' % str(e))
  7070. self.inform.emit('[ERROR] %s %s' %
  7071. (_('App.on_fileopenscript() -->'), str(e)))
  7072. return
  7073. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7074. self.handleTextChanged()
  7075. # self.ui.show()
  7076. except Exception as e:
  7077. log.debug("App.on_fileopenscript() -> %s" % str(e))
  7078. def on_filerunscript(self, name=None):
  7079. """
  7080. File menu callback for loading and running a TCL script.
  7081. :return: None
  7082. """
  7083. self.report_usage("on_filerunscript")
  7084. App.log.debug("on_file_runscript()")
  7085. if name:
  7086. filename = name
  7087. else:
  7088. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7089. try:
  7090. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7091. directory=self.get_last_folder(), filter=_filter_)
  7092. except TypeError:
  7093. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7094. # The Qt methods above will return a QString which can cause problems later.
  7095. # So far json.dump() will fail to serialize it.
  7096. # TODO: Improve the serialization methods and remove this fix.
  7097. filename = str(filename)
  7098. if filename == "":
  7099. self.inform.emit('[WARNING_NOTCL] %s' %
  7100. _("Run TCL script cancelled."))
  7101. else:
  7102. try:
  7103. with open(filename, "r") as tcl_script:
  7104. cmd_line_shellfile_content = tcl_script.read()
  7105. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7106. except Exception as e:
  7107. log.debug("App.on_filerunscript() -> %s" % str(e))
  7108. sys.exit(2)
  7109. def on_file_saveproject(self):
  7110. """
  7111. Callback for menu item File->Save Project. Saves the project to
  7112. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7113. if set to None. The project is saved by calling ``self.save_project()``.
  7114. :return: None
  7115. """
  7116. self.report_usage("on_file_saveproject")
  7117. if self.project_filename is None:
  7118. self.on_file_saveprojectas()
  7119. else:
  7120. self.worker_task.emit({'fcn': self.save_project,
  7121. 'params': [self.project_filename]})
  7122. if self.defaults["global_open_style"] is False:
  7123. self.file_opened.emit("project", self.project_filename)
  7124. self.file_saved.emit("project", self.project_filename)
  7125. self.set_ui_title(name=self.project_filename)
  7126. self.should_we_save = False
  7127. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7128. """
  7129. Callback for menu item File->Save Project As... Opens a file
  7130. chooser and saves the project to the given file via
  7131. ``self.save_project()``.
  7132. :param make_copy if to be create a copy of the project; boolean
  7133. :param use_thread: if to be run in a separate thread; boolean
  7134. :param quit_action: if to be followed by quiting the application; boolean
  7135. :return: None
  7136. """
  7137. self.report_usage("on_file_saveprojectas")
  7138. self.date = str(datetime.today()).rpartition('.')[0]
  7139. self.date = ''.join(c for c in self.date if c not in ':-')
  7140. self.date = self.date.replace(' ', '_')
  7141. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7142. try:
  7143. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7144. caption=_("Save Project As ..."),
  7145. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7146. filter=filter_)
  7147. except TypeError:
  7148. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7149. filename = str(filename)
  7150. if filename == '':
  7151. self.inform.emit('[WARNING_NOTCL] %s' %
  7152. _("Save Project cancelled."))
  7153. return
  7154. try:
  7155. f = open(filename, 'r')
  7156. f.close()
  7157. except IOError:
  7158. pass
  7159. if use_thread is True:
  7160. self.worker_task.emit({'fcn': self.save_project,
  7161. 'params': [filename, quit_action]})
  7162. else:
  7163. self.save_project(filename, quit_action)
  7164. # self.save_project(filename)
  7165. if self.defaults["global_open_style"] is False:
  7166. self.file_opened.emit("project", filename)
  7167. self.file_saved.emit("project", filename)
  7168. if not make_copy:
  7169. self.project_filename = filename
  7170. self.set_ui_title(name=self.project_filename)
  7171. self.should_we_save = False
  7172. def export_svg(self, obj_name, filename, scale_factor=0.00):
  7173. """
  7174. Exports a Geometry Object to an SVG file.
  7175. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7176. :param filename: Path to the SVG file to save to.
  7177. :param scale_factor: factor by which to change/scale the thickness of the features
  7178. :return:
  7179. """
  7180. self.report_usage("export_svg()")
  7181. if filename is None:
  7182. filename = self.defaults["global_last_save_folder"]
  7183. self.log.debug("export_svg()")
  7184. try:
  7185. obj = self.collection.get_by_name(str(obj_name))
  7186. except:
  7187. # TODO: The return behavior has not been established... should raise exception?
  7188. return "Could not retrieve object: %s" % obj_name
  7189. with self.proc_container.new(_("Exporting SVG")) as proc:
  7190. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7191. # Determine bounding area for svg export
  7192. bounds = obj.bounds()
  7193. size = obj.size()
  7194. # Convert everything to strings for use in the xml doc
  7195. svgwidth = str(size[0])
  7196. svgheight = str(size[1])
  7197. minx = str(bounds[0])
  7198. miny = str(bounds[1] - size[1])
  7199. uom = obj.units.lower()
  7200. # Add a SVG Header and footer to the svg output from shapely
  7201. # The transform flips the Y Axis so that everything renders
  7202. # properly within svg apps such as inkscape
  7203. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7204. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7205. svg_header += 'width="' + svgwidth + uom + '" '
  7206. svg_header += 'height="' + svgheight + uom + '" '
  7207. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7208. svg_header += '<g transform="scale(1,-1)">'
  7209. svg_footer = '</g> </svg>'
  7210. svg_elem = svg_header + exported_svg + svg_footer
  7211. # Parse the xml through a xml parser just to add line feeds
  7212. # and to make it look more pretty for the output
  7213. svgcode = parse_xml_string(svg_elem)
  7214. try:
  7215. with open(filename, 'w') as fp:
  7216. fp.write(svgcode.toprettyxml())
  7217. except PermissionError:
  7218. self.inform.emit('[WARNING] %s' %
  7219. _("Permission denied, saving not possible.\n"
  7220. "Most likely another app is holding the file open and not accessible."))
  7221. return 'fail'
  7222. if self.defaults["global_open_style"] is False:
  7223. self.file_opened.emit("SVG", filename)
  7224. self.file_saved.emit("SVG", filename)
  7225. self.inform.emit('[success] %s: %s' %
  7226. (_("SVG file exported to"), filename))
  7227. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  7228. """
  7229. Exports a Geometry Object to an SVG file in negative.
  7230. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7231. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7232. :param filename: Path to the SVG file to save to.
  7233. :param boundary: thickness of a black border to surround all the features
  7234. :param scale_factor: factor by which to change/scale the thickness of the features
  7235. :param use_thread: if to be run in a separate thread; boolean
  7236. :return:
  7237. """
  7238. self.report_usage("export_negative()")
  7239. if filename is None:
  7240. filename = self.defaults["global_last_save_folder"]
  7241. self.log.debug("export_svg() negative")
  7242. try:
  7243. obj = self.collection.get_by_name(str(obj_name))
  7244. except:
  7245. # TODO: The return behavior has not been established... should raise exception?
  7246. return "Could not retrieve object: %s" % obj_name
  7247. try:
  7248. box = self.collection.get_by_name(str(box_name))
  7249. except:
  7250. # TODO: The return behavior has not been established... should raise exception?
  7251. return "Could not retrieve object: %s" % box_name
  7252. if box is None:
  7253. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7254. (_("No object Box. Using instead"), obj))
  7255. box = obj
  7256. def make_negative_film():
  7257. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7258. # Determine bounding area for svg export
  7259. bounds = box.bounds()
  7260. size = box.size()
  7261. uom = obj.units.lower()
  7262. # Convert everything to strings for use in the xml doc
  7263. svgwidth = str(size[0] + (2 * boundary))
  7264. svgheight = str(size[1] + (2 * boundary))
  7265. minx = str(bounds[0] - boundary)
  7266. miny = str(bounds[1] + boundary + size[1])
  7267. miny_rect = str(bounds[1] - boundary)
  7268. # Add a SVG Header and footer to the svg output from shapely
  7269. # The transform flips the Y Axis so that everything renders
  7270. # properly within svg apps such as inkscape
  7271. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7272. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7273. svg_header += 'width="' + svgwidth + uom + '" '
  7274. svg_header += 'height="' + svgheight + uom + '" '
  7275. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7276. svg_header += '>'
  7277. svg_header += '<g transform="scale(1,-1)">'
  7278. svg_footer = '</g> </svg>'
  7279. # Change the attributes of the exported SVG
  7280. # We don't need stroke-width - wrong, we do when we have lines with certain width
  7281. # We set opacity to maximum
  7282. # We set the color to WHITE
  7283. root = ET.fromstring(exported_svg)
  7284. for child in root:
  7285. child.set('fill', '#FFFFFF')
  7286. child.set('opacity', '1.0')
  7287. child.set('stroke', '#FFFFFF')
  7288. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  7289. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  7290. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  7291. first_svg_elem_tag = 'rect'
  7292. first_svg_elem_attribs = {
  7293. 'x': minx,
  7294. 'y': miny_rect,
  7295. 'width': svgwidth,
  7296. 'height': svgheight,
  7297. 'id': 'neg_rect',
  7298. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  7299. }
  7300. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  7301. exported_svg = ET.tostring(root)
  7302. svg_elem = svg_header + str(exported_svg) + svg_footer
  7303. # Parse the xml through a xml parser just to add line feeds
  7304. # and to make it look more pretty for the output
  7305. doc = parse_xml_string(svg_elem)
  7306. try:
  7307. with open(filename, 'w') as fp:
  7308. fp.write(doc.toprettyxml())
  7309. except PermissionError:
  7310. self.inform.emit('[WARNING] %s' %
  7311. _("Permission denied, saving not possible.\n"
  7312. "Most likely another app is holding the file open and not accessible."))
  7313. return 'fail'
  7314. if self.defaults["global_open_style"] is False:
  7315. self.file_opened.emit("SVG", filename)
  7316. self.file_saved.emit("SVG", filename)
  7317. self.inform.emit('[success] %s: %s' %
  7318. (_("SVG file exported to"), filename))
  7319. if use_thread is True:
  7320. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7321. def job_thread_film(app_obj):
  7322. try:
  7323. make_negative_film()
  7324. except Exception as e:
  7325. proc.done()
  7326. return
  7327. proc.done()
  7328. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7329. else:
  7330. make_negative_film()
  7331. def export_svg_positive(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  7332. """
  7333. Exports a Geometry Object to an SVG file in positive black.
  7334. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7335. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7336. :param filename: Path to the SVG file to save to.
  7337. :param scale_factor: factor by which to change/scale the thickness of the features
  7338. :param use_thread: if to be run in a separate thread; boolean
  7339. :return:
  7340. """
  7341. self.report_usage("export_svg_positive()")
  7342. if filename is None:
  7343. filename = self.defaults["global_last_save_folder"]
  7344. self.log.debug("export_svg() black")
  7345. try:
  7346. obj = self.collection.get_by_name(str(obj_name))
  7347. except:
  7348. # TODO: The return behavior has not been established... should raise exception?
  7349. return "Could not retrieve object: %s" % obj_name
  7350. try:
  7351. box = self.collection.get_by_name(str(box_name))
  7352. except:
  7353. # TODO: The return behavior has not been established... should raise exception?
  7354. return "Could not retrieve object: %s" % box_name
  7355. if box is None:
  7356. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7357. (_("No object Box. Using instead"), obj))
  7358. box = obj
  7359. def make_positive_film():
  7360. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7361. self.progress.emit(40)
  7362. # Change the attributes of the exported SVG
  7363. # We don't need stroke-width
  7364. # We set opacity to maximum
  7365. # We set the colour to WHITE
  7366. root = ET.fromstring(exported_svg)
  7367. for child in root:
  7368. child.set('fill', str(self.defaults['tools_film_color']))
  7369. child.set('opacity', '1.0')
  7370. child.set('stroke', str(self.defaults['tools_film_color']))
  7371. exported_svg = ET.tostring(root)
  7372. # Determine bounding area for svg export
  7373. bounds = box.bounds()
  7374. size = box.size()
  7375. # This contain the measure units
  7376. uom = obj.units.lower()
  7377. # Define a boundary around SVG of about 1.0mm (~39mils)
  7378. if uom in "mm":
  7379. boundary = 1.0
  7380. else:
  7381. boundary = 0.0393701
  7382. self.progress.emit(80)
  7383. # Convert everything to strings for use in the xml doc
  7384. svgwidth = str(size[0] + (2 * boundary))
  7385. svgheight = str(size[1] + (2 * boundary))
  7386. minx = str(bounds[0] - boundary)
  7387. miny = str(bounds[1] + boundary + size[1])
  7388. self.log.debug(minx)
  7389. self.log.debug(miny)
  7390. # Add a SVG Header and footer to the svg output from shapely
  7391. # The transform flips the Y Axis so that everything renders
  7392. # properly within svg apps such as inkscape
  7393. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7394. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7395. svg_header += 'width="' + svgwidth + uom + '" '
  7396. svg_header += 'height="' + svgheight + uom + '" '
  7397. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7398. svg_header += '>'
  7399. svg_header += '<g transform="scale(1,-1)">'
  7400. svg_footer = '</g> </svg>'
  7401. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  7402. self.progress.emit(90)
  7403. # Parse the xml through a xml parser just to add line feeds
  7404. # and to make it look more pretty for the output
  7405. doc = parse_xml_string(svg_elem)
  7406. try:
  7407. with open(filename, 'w') as fp:
  7408. fp.write(doc.toprettyxml())
  7409. except PermissionError:
  7410. self.inform.emit('[WARNING] %s' %
  7411. _("Permission denied, saving not possible.\n"
  7412. "Most likely another app is holding the file open and not accessible."))
  7413. return 'fail'
  7414. self.progress.emit(100)
  7415. if self.defaults["global_open_style"] is False:
  7416. self.file_opened.emit("SVG", filename)
  7417. self.file_saved.emit("SVG", filename)
  7418. self.inform.emit('[success] %s: %s' %
  7419. (_("SVG file exported to"), filename))
  7420. if use_thread is True:
  7421. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7422. def job_thread_film(app_obj):
  7423. try:
  7424. make_positive_film()
  7425. except Exception as e:
  7426. proc.done()
  7427. return
  7428. proc.done()
  7429. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7430. else:
  7431. make_positive_film()
  7432. def save_source_file(self, obj_name, filename, use_thread=True):
  7433. """
  7434. Exports a FlatCAM Object to an Gerber/Excellon file.
  7435. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7436. :param filename: Path to the Gerber file to save to.
  7437. :param use_thread: if to be run in a separate thread
  7438. :return:
  7439. """
  7440. self.report_usage("save source file()")
  7441. if filename is None:
  7442. filename = self.defaults["global_last_save_folder"]
  7443. self.log.debug("save source file()")
  7444. obj = self.collection.get_by_name(obj_name)
  7445. file_string = StringIO(obj.source_file)
  7446. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7447. try:
  7448. with open(filename, 'w') as file:
  7449. file.writelines('G04*\n')
  7450. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7451. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7452. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7453. file.writelines('G04 Created on : %s*\n' % time_string)
  7454. for line in file_string:
  7455. file.writelines(line)
  7456. except PermissionError:
  7457. self.inform.emit('[WARNING] %s' %
  7458. _("Permission denied, saving not possible.\n"
  7459. "Most likely another app is holding the file open and not accessible."))
  7460. return 'fail'
  7461. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7462. """
  7463. Exports a Excellon Object to an Excellon file.
  7464. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7465. :param filename: Path to the Excellon file to save to.
  7466. :param use_thread: if to be run in a separate thread
  7467. :return:
  7468. """
  7469. self.report_usage("export_excellon()")
  7470. if filename is None:
  7471. filename = self.defaults["global_last_save_folder"]
  7472. self.log.debug("export_excellon()")
  7473. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7474. self.defaults["excellon_exp_decimals"]
  7475. )
  7476. units = ''
  7477. if local_use is None:
  7478. try:
  7479. obj = self.collection.get_by_name(str(obj_name))
  7480. except:
  7481. # TODO: The return behavior has not been established... should raise exception?
  7482. return "Could not retrieve object: %s" % obj_name
  7483. else:
  7484. obj = local_use
  7485. # updated units
  7486. eunits = self.defaults["excellon_exp_units"]
  7487. ewhole = self.defaults["excellon_exp_integer"]
  7488. efract = self.defaults["excellon_exp_decimals"]
  7489. ezeros = self.defaults["excellon_exp_zeros"]
  7490. eformat = self.defaults["excellon_exp_format"]
  7491. slot_type = self.defaults["excellon_exp_slot_type"]
  7492. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7493. if fc_units == 'MM':
  7494. factor = 1 if eunits == 'METRIC' else 0.03937
  7495. else:
  7496. factor = 25.4 if eunits == 'METRIC' else 1
  7497. def make_excellon():
  7498. try:
  7499. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7500. header = 'M48\n'
  7501. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7502. (str(self.version), str(self.version_date))
  7503. header += ';Filename: %s' % str(obj_name) + '\n'
  7504. header += ';Created on : %s' % time_str + '\n'
  7505. if eformat == 'dec':
  7506. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7507. header += eunits + '\n'
  7508. for tool in obj.tools:
  7509. if eunits == 'METRIC':
  7510. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7511. tool=str(tool),
  7512. dec=2)
  7513. else:
  7514. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7515. tool=str(tool),
  7516. dec=4)
  7517. else:
  7518. if ezeros == 'LZ':
  7519. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7520. form='ndec', e_zeros='LZ', factor=factor,
  7521. slot_type=slot_type)
  7522. header += '%s,%s\n' % (eunits, 'LZ')
  7523. header += format_exc
  7524. for tool in obj.tools:
  7525. if eunits == 'METRIC':
  7526. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7527. tool=str(tool),
  7528. dec=2)
  7529. else:
  7530. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7531. tool=str(tool),
  7532. dec=4)
  7533. else:
  7534. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7535. form='ndec', e_zeros='TZ', factor=factor,
  7536. slot_type=slot_type)
  7537. header += '%s,%s\n' % (eunits, 'TZ')
  7538. header += format_exc
  7539. for tool in obj.tools:
  7540. if eunits == 'METRIC':
  7541. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7542. tool=str(tool),
  7543. dec=2)
  7544. else:
  7545. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7546. tool=str(tool),
  7547. dec=4)
  7548. header += '%\n'
  7549. footer = 'M30\n'
  7550. exported_excellon = header
  7551. exported_excellon += excellon_code
  7552. exported_excellon += footer
  7553. if local_use is None:
  7554. try:
  7555. with open(filename, 'w') as fp:
  7556. fp.write(exported_excellon)
  7557. except PermissionError:
  7558. self.inform.emit('[WARNING] %s' %
  7559. _("Permission denied, saving not possible.\n"
  7560. "Most likely another app is holding the file open and not accessible."))
  7561. return 'fail'
  7562. if self.defaults["global_open_style"] is False:
  7563. self.file_opened.emit("Excellon", filename)
  7564. self.file_saved.emit("Excellon", filename)
  7565. self.inform.emit('[success] %s: %s' %
  7566. (_("Excellon file exported to"), filename))
  7567. else:
  7568. return exported_excellon
  7569. except Exception as e:
  7570. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7571. return 'fail'
  7572. if use_thread is True:
  7573. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7574. def job_thread_exc(app_obj):
  7575. ret = make_excellon()
  7576. if ret == 'fail':
  7577. self.inform.emit('[ERROR_NOTCL] %s' %
  7578. _('Could not export Excellon file.'))
  7579. return
  7580. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7581. else:
  7582. ret = make_excellon()
  7583. if ret == 'fail':
  7584. self.inform.emit('[ERROR_NOTCL] %s' %
  7585. _('Could not export Excellon file.'))
  7586. return 'fail'
  7587. if local_use is not None:
  7588. return ret
  7589. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7590. """
  7591. Exports a Gerber Object to an Gerber file.
  7592. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7593. :param filename: Path to the Gerber file to save to.
  7594. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7595. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7596. :param use_thread: if to be run in a separate thread
  7597. :return:
  7598. """
  7599. self.report_usage("export_gerber()")
  7600. if filename is None:
  7601. filename = self.defaults["global_last_save_folder"]
  7602. self.log.debug("export_gerber()")
  7603. if local_use is None:
  7604. try:
  7605. obj = self.collection.get_by_name(str(obj_name))
  7606. except:
  7607. # TODO: The return behavior has not been established... should raise exception?
  7608. return "Could not retrieve object: %s" % obj_name
  7609. else:
  7610. obj = local_use
  7611. # updated units
  7612. gunits = self.defaults["gerber_exp_units"]
  7613. gwhole = self.defaults["gerber_exp_integer"]
  7614. gfract = self.defaults["gerber_exp_decimals"]
  7615. gzeros = self.defaults["gerber_exp_zeros"]
  7616. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7617. if fc_units == 'MM':
  7618. factor = 1 if gunits == 'MM' else 0.03937
  7619. else:
  7620. factor = 25.4 if gunits == 'MM' else 1
  7621. def make_gerber():
  7622. try:
  7623. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7624. header = 'G04*\n'
  7625. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7626. (str(self.version), str(self.version_date))
  7627. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7628. header += 'G04 Created on : %s*' % time_str + '\n'
  7629. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7630. header += "%MO{units}*%\n".format(units=gunits)
  7631. for apid in obj.apertures:
  7632. if obj.apertures[apid]['type'] == 'C':
  7633. header += "%ADD{apid}{type},{size}*%\n".format(
  7634. apid=str(apid),
  7635. type='C',
  7636. size=(factor * obj.apertures[apid]['size'])
  7637. )
  7638. elif obj.apertures[apid]['type'] == 'R':
  7639. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7640. apid=str(apid),
  7641. type='R',
  7642. width=(factor * obj.apertures[apid]['width']),
  7643. height=(factor * obj.apertures[apid]['height'])
  7644. )
  7645. elif obj.apertures[apid]['type'] == 'O':
  7646. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7647. apid=str(apid),
  7648. type='O',
  7649. width=(factor * obj.apertures[apid]['width']),
  7650. height=(factor * obj.apertures[apid]['height'])
  7651. )
  7652. header += '\n'
  7653. # obsolete units but some software may need it
  7654. if gunits == 'IN':
  7655. header += 'G70*\n'
  7656. else:
  7657. header += 'G71*\n'
  7658. # Absolute Mode
  7659. header += 'G90*\n'
  7660. header += 'G01*\n'
  7661. # positive polarity
  7662. header += '%LPD*%\n'
  7663. footer = 'M02*\n'
  7664. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7665. exported_gerber = header
  7666. exported_gerber += gerber_code
  7667. exported_gerber += footer
  7668. if local_use is None:
  7669. try:
  7670. with open(filename, 'w') as fp:
  7671. fp.write(exported_gerber)
  7672. except PermissionError:
  7673. self.inform.emit('[WARNING] %s' %
  7674. _("Permission denied, saving not possible.\n"
  7675. "Most likely another app is holding the file open and not accessible."))
  7676. return 'fail'
  7677. if self.defaults["global_open_style"] is False:
  7678. self.file_opened.emit("Gerber", filename)
  7679. self.file_saved.emit("Gerber", filename)
  7680. self.inform.emit('[success] %s: %s' %
  7681. (_("Gerber file exported to"), filename))
  7682. else:
  7683. return exported_gerber
  7684. except Exception as e:
  7685. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7686. return 'fail'
  7687. if use_thread is True:
  7688. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7689. def job_thread_grb(app_obj):
  7690. ret = make_gerber()
  7691. if ret == 'fail':
  7692. self.inform.emit('[ERROR_NOTCL] %s' %
  7693. _('Could not export Gerber file.'))
  7694. return
  7695. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7696. else:
  7697. ret = make_gerber()
  7698. if ret == 'fail':
  7699. self.inform.emit('[ERROR_NOTCL] %s' %
  7700. _('Could not export Gerber file.'))
  7701. return 'fail'
  7702. if local_use is not None:
  7703. return ret
  7704. def export_dxf(self, obj_name, filename, use_thread=True):
  7705. """
  7706. Exports a Geometry Object to an DXF file.
  7707. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7708. :param filename: Path to the DXF file to save to.
  7709. :param use_thread: if to be run in a separate thread
  7710. :return:
  7711. """
  7712. self.report_usage("export_dxf()")
  7713. if filename is None:
  7714. filename = self.defaults["global_last_save_folder"]
  7715. self.log.debug("export_dxf()")
  7716. format_exc = ''
  7717. units = ''
  7718. try:
  7719. obj = self.collection.get_by_name(str(obj_name))
  7720. except:
  7721. # TODO: The return behavior has not been established... should raise exception?
  7722. return "Could not retrieve object: %s" % obj_name
  7723. # updated units
  7724. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7725. if units == 'IN' or units == 'INCH':
  7726. units = 'INCH'
  7727. elif units == 'MM' or units == 'METIRC':
  7728. units ='METRIC'
  7729. def make_dxf():
  7730. try:
  7731. dxf_code = obj.export_dxf()
  7732. dxf_code.saveas(filename)
  7733. if self.defaults["global_open_style"] is False:
  7734. self.file_opened.emit("DXF", filename)
  7735. self.file_saved.emit("DXF", filename)
  7736. self.inform.emit('[success] %s: %s' %
  7737. (_("DXF file exported to"), filename))
  7738. except:
  7739. return 'fail'
  7740. if use_thread is True:
  7741. with self.proc_container.new(_("Exporting DXF")) as proc:
  7742. def job_thread_exc(app_obj):
  7743. ret = make_dxf()
  7744. if ret == 'fail':
  7745. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  7746. _('Could not export DXF file.'))
  7747. return
  7748. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7749. else:
  7750. ret = make_dxf()
  7751. if ret == 'fail':
  7752. self.inform.emit('[WARNING_NOTCL] %s' %
  7753. _('Could not export DXF file.'))
  7754. return
  7755. def import_svg(self, filename, geo_type='geometry', outname=None):
  7756. """
  7757. Adds a new Geometry Object to the projects and populates
  7758. it with shapes extracted from the SVG file.
  7759. :param filename: Path to the SVG file.
  7760. :param outname:
  7761. :return:
  7762. """
  7763. self.report_usage("import_svg()")
  7764. obj_type = ""
  7765. if geo_type is None or geo_type == "geometry":
  7766. obj_type = "geometry"
  7767. elif geo_type == "gerber":
  7768. obj_type = geo_type
  7769. else:
  7770. self.inform.emit('[ERROR_NOTCL] %s' %
  7771. _("Not supported type is picked as parameter. "
  7772. "Only Geometry and Gerber are supported"))
  7773. return
  7774. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7775. def obj_init(geo_obj, app_obj):
  7776. geo_obj.import_svg(filename, obj_type, units=units)
  7777. geo_obj.multigeo = False
  7778. with self.proc_container.new(_("Importing SVG")) as proc:
  7779. # Object name
  7780. name = outname or filename.split('/')[-1].split('\\')[-1]
  7781. self.new_object(obj_type, name, obj_init, autoselected=False)
  7782. self.progress.emit(20)
  7783. # Register recent file
  7784. self.file_opened.emit("svg", filename)
  7785. # GUI feedback
  7786. self.inform.emit('[success] %s: %s' %
  7787. (_("Opened"), filename))
  7788. self.progress.emit(100)
  7789. def import_dxf(self, filename, geo_type='geometry', outname=None):
  7790. """
  7791. Adds a new Geometry Object to the projects and populates
  7792. it with shapes extracted from the DXF file.
  7793. :param filename: Path to the DXF file.
  7794. :param outname:
  7795. :type putname: str
  7796. :return:
  7797. """
  7798. self.report_usage("import_dxf()")
  7799. obj_type = ""
  7800. if geo_type is None or geo_type == "geometry":
  7801. obj_type = "geometry"
  7802. elif geo_type == "gerber":
  7803. obj_type = geo_type
  7804. else:
  7805. self.inform.emit('[ERROR_NOTCL] %s' %
  7806. _("Not supported type is picked as parameter. "
  7807. "Only Geometry and Gerber are supported"))
  7808. return
  7809. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7810. def obj_init(geo_obj, app_obj):
  7811. geo_obj.import_dxf(filename, obj_type, units=units)
  7812. geo_obj.multigeo = False
  7813. with self.proc_container.new(_("Importing DXF")) as proc:
  7814. # Object name
  7815. name = outname or filename.split('/')[-1].split('\\')[-1]
  7816. self.new_object(obj_type, name, obj_init, autoselected=False)
  7817. self.progress.emit(20)
  7818. # Register recent file
  7819. self.file_opened.emit("dxf", filename)
  7820. # GUI feedback
  7821. self.inform.emit('[success] %s: %s' %
  7822. (_("Opened"), filename))
  7823. self.progress.emit(100)
  7824. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  7825. """
  7826. Adds a new Geometry Object to the projects and populates
  7827. it with shapes extracted from the SVG file.
  7828. :param filename: Path to the SVG file.
  7829. :param o_type: type of FlatCAM objeect
  7830. :param dpi: dot per inch
  7831. :param mode: black or color
  7832. :param mask: dictate the level of detail
  7833. :param outname: name for the resulting file
  7834. :return:
  7835. """
  7836. self.report_usage("import_image()")
  7837. if o_type is None or o_type == "geometry":
  7838. obj_type = "geometry"
  7839. elif o_type == "gerber":
  7840. obj_type = o_type
  7841. else:
  7842. self.inform.emit('[ERROR_NOTCL] %s' %
  7843. _("Not supported type is picked as parameter. "
  7844. "Only Geometry and Gerber are supported"))
  7845. return
  7846. def obj_init(geo_obj, app_obj):
  7847. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  7848. geo_obj.multigeo = False
  7849. with self.proc_container.new(_("Importing Image")) as proc:
  7850. # Object name
  7851. name = outname or filename.split('/')[-1].split('\\')[-1]
  7852. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  7853. self.new_object(obj_type, name, obj_init)
  7854. self.progress.emit(20)
  7855. # Register recent file
  7856. self.file_opened.emit("image", filename)
  7857. # GUI feedback
  7858. self.inform.emit('[success] %s: %s' %
  7859. (_("Opened"), filename))
  7860. self.progress.emit(100)
  7861. def open_gerber(self, filename, outname=None):
  7862. """
  7863. Opens a Gerber file, parses it and creates a new object for
  7864. it in the program. Thread-safe.
  7865. :param outname: Name of the resulting object. None causes the
  7866. name to be that of the file.
  7867. :param filename: Gerber file filename
  7868. :type filename: str
  7869. :param follow: If true, the parser will not create polygons, just lines
  7870. following the gerber path.
  7871. :type follow: bool
  7872. :return: None
  7873. """
  7874. # How the object should be initialized
  7875. def obj_init(gerber_obj, app_obj):
  7876. assert isinstance(gerber_obj, FlatCAMGerber), \
  7877. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  7878. # Opening the file happens here
  7879. self.progress.emit(30)
  7880. try:
  7881. gerber_obj.parse_file(filename)
  7882. except IOError:
  7883. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7884. (_("Failed to open file"), filename))
  7885. app_obj.progress.emit(0)
  7886. return "fail"
  7887. except ParseError as err:
  7888. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  7889. (_("Failed to parse file"), filename, str(err)))
  7890. app_obj.progress.emit(0)
  7891. self.log.error(str(err))
  7892. return "fail"
  7893. except Exception as e:
  7894. log.debug("App.open_gerber() --> %s" % str(e))
  7895. msg = '[ERROR] %s' % \
  7896. _("An internal error has occurred. See shell.\n")
  7897. msg += traceback.format_exc()
  7898. app_obj.inform.emit(msg)
  7899. return "fail"
  7900. if gerber_obj.is_empty():
  7901. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  7902. # self.collection.set_active(gerber_obj.options["name"])
  7903. # self.collection.delete_active()
  7904. self.inform.emit('[ERROR_NOTCL] %s' %
  7905. _("Object is not Gerber file or empty. Aborting object creation."))
  7906. return "fail"
  7907. # Further parsing
  7908. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  7909. App.log.debug("open_gerber()")
  7910. with self.proc_container.new(_("Opening Gerber")) as proc:
  7911. self.progress.emit(10)
  7912. # Object name
  7913. name = outname or filename.split('/')[-1].split('\\')[-1]
  7914. # # ## Object creation # ##
  7915. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  7916. if ret == 'fail':
  7917. self.inform.emit('[ERROR_NOTCL]%s' %
  7918. _(' Open Gerber failed. Probable not a Gerber file.'))
  7919. return
  7920. # Register recent file
  7921. self.file_opened.emit("gerber", filename)
  7922. self.progress.emit(100)
  7923. # GUI feedback
  7924. self.inform.emit('[success] %s: %s' %
  7925. (_("Opened"), filename))
  7926. def open_excellon(self, filename, outname=None, plot=True):
  7927. """
  7928. Opens an Excellon file, parses it and creates a new object for
  7929. it in the program. Thread-safe.
  7930. :param outname: Name of the resulting object. None causes the
  7931. name to be that of the file.
  7932. :param filename: Excellon file filename
  7933. :type filename: str
  7934. :return: None
  7935. """
  7936. App.log.debug("open_excellon()")
  7937. # How the object should be initialized
  7938. def obj_init(excellon_obj, app_obj):
  7939. # self.progress.emit(20)
  7940. try:
  7941. ret = excellon_obj.parse_file(filename=filename)
  7942. if ret == "fail":
  7943. log.debug("Excellon parsing failed.")
  7944. self.inform.emit('[ERROR_NOTCL] %s' %
  7945. _("This is not Excellon file."))
  7946. return "fail"
  7947. except IOError:
  7948. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7949. (_("Cannot open file"), filename))
  7950. log.debug("Could not open Excellon object.")
  7951. self.progress.emit(0) # TODO: self and app_bjj mixed
  7952. return "fail"
  7953. except:
  7954. msg = '[ERROR_NOTCL] %s' % \
  7955. _("An internal error has occurred. See shell.\n")
  7956. msg += traceback.format_exc()
  7957. app_obj.inform.emit(msg)
  7958. return "fail"
  7959. ret = excellon_obj.create_geometry()
  7960. if ret == 'fail':
  7961. log.debug("Could not create geometry for Excellon object.")
  7962. return "fail"
  7963. for tool in excellon_obj.tools:
  7964. if excellon_obj.tools[tool]['solid_geometry']:
  7965. return
  7966. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7967. (_("No geometry found in file"), filename))
  7968. return "fail"
  7969. with self.proc_container.new(_("Opening Excellon.")):
  7970. # Object name
  7971. name = outname or filename.split('/')[-1].split('\\')[-1]
  7972. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7973. if ret_val == 'fail':
  7974. self.inform.emit('[ERROR_NOTCL] %s' %
  7975. _('Open Excellon file failed. Probable not an Excellon file.'))
  7976. return
  7977. # Register recent file
  7978. self.file_opened.emit("excellon", filename)
  7979. # GUI feedback
  7980. self.inform.emit('[success] %s: %s' %
  7981. (_("Opened"), filename))
  7982. def open_gcode(self, filename, outname=None, plot=True):
  7983. """
  7984. Opens a G-gcode file, parses it and creates a new object for
  7985. it in the program. Thread-safe.
  7986. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7987. :param filename: G-code file filename
  7988. :type filename: str
  7989. :return: None
  7990. """
  7991. App.log.debug("open_gcode()")
  7992. # How the object should be initialized
  7993. def obj_init(job_obj, app_obj_):
  7994. """
  7995. :param job_obj: the resulting object
  7996. :type app_obj_: App
  7997. """
  7998. assert isinstance(app_obj_, App), \
  7999. "Initializer expected App, got %s" % type(app_obj_)
  8000. self.progress.emit(10)
  8001. try:
  8002. f = open(filename)
  8003. gcode = f.read()
  8004. f.close()
  8005. except IOError:
  8006. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8007. (_("Failed to open"), filename))
  8008. self.progress.emit(0)
  8009. return "fail"
  8010. job_obj.gcode = gcode
  8011. self.progress.emit(20)
  8012. ret = job_obj.gcode_parse()
  8013. if ret == "fail":
  8014. self.inform.emit('[ERROR_NOTCL] %s' %
  8015. _("This is not GCODE"))
  8016. return "fail"
  8017. self.progress.emit(60)
  8018. job_obj.create_geometry()
  8019. with self.proc_container.new(_("Opening G-Code.")):
  8020. # Object name
  8021. name = outname or filename.split('/')[-1].split('\\')[-1]
  8022. # New object creation and file processing
  8023. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8024. if ret == 'fail':
  8025. self.inform.emit('[ERROR_NOTCL] %s' %
  8026. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  8027. "Attempting to create a FlatCAM CNCJob Object from "
  8028. "G-Code file failed during processing"))
  8029. return "fail"
  8030. # Register recent file
  8031. self.file_opened.emit("cncjob", filename)
  8032. # GUI feedback
  8033. self.inform.emit('[success] %s: %s' %
  8034. (_("Opened"), filename))
  8035. self.progress.emit(100)
  8036. def open_config_file(self, filename, run_from_arg=None):
  8037. """
  8038. Loads a config file from the specified file.
  8039. :param filename: Name of the file from which to load.
  8040. :type filename: str
  8041. :return: None
  8042. """
  8043. App.log.debug("Opening config file: " + filename)
  8044. # add the tab if it was closed
  8045. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  8046. # first clear previous text in text editor (if any)
  8047. self.ui.code_editor.clear()
  8048. # Switch plot_area to CNCJob tab
  8049. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  8050. try:
  8051. if filename:
  8052. f = QtCore.QFile(filename)
  8053. if f.open(QtCore.QIODevice.ReadOnly):
  8054. stream = QtCore.QTextStream(f)
  8055. gcode_edited = stream.readAll()
  8056. self.ui.code_editor.setPlainText(gcode_edited)
  8057. f.close()
  8058. except IOError:
  8059. App.log.error("Failed to open config file: %s" % filename)
  8060. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8061. (_("Failed to open config file"), filename))
  8062. return
  8063. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8064. """
  8065. Loads a project from the specified file.
  8066. 1) Loads and parses file
  8067. 2) Registers the file as recently opened.
  8068. 3) Calls on_file_new()
  8069. 4) Updates options
  8070. 5) Calls new_object() with the object's from_dict() as init method.
  8071. 6) Calls plot_all() if plot=True
  8072. :param filename: Name of the file from which to load.
  8073. :type filename: str
  8074. :param run_from_arg: True if run for arguments
  8075. :param plot: If True plot all objects in the project
  8076. :param cli: run from command line
  8077. :return: None
  8078. """
  8079. App.log.debug("Opening project: " + filename)
  8080. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8081. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8082. if cli is None:
  8083. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8084. # Open and parse an uncompressed Project file
  8085. try:
  8086. f = open(filename, 'r')
  8087. except IOError:
  8088. App.log.error("Failed to open project file: %s" % filename)
  8089. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8090. (_("Failed to open project file"), filename))
  8091. return
  8092. try:
  8093. d = json.load(f, object_hook=dict2obj)
  8094. except Exception as e:
  8095. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8096. (filename, str(e)))
  8097. f.close()
  8098. # Open and parse a compressed Project file
  8099. try:
  8100. with lzma.open(filename) as f:
  8101. file_content = f.read().decode('utf-8')
  8102. d = json.loads(file_content, object_hook=dict2obj)
  8103. except Exception as e:
  8104. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8105. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8106. (_("Failed to open project file"), filename))
  8107. return
  8108. # Clear the current project
  8109. # # NOT THREAD SAFE # ##
  8110. if run_from_arg is True:
  8111. pass
  8112. elif cli is True:
  8113. self.delete_selection_shape()
  8114. else:
  8115. self.on_file_new()
  8116. # Project options
  8117. self.options.update(d['options'])
  8118. self.project_filename = filename
  8119. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8120. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8121. if cli is None:
  8122. self.set_screen_units(self.options["units"])
  8123. # Re create objects
  8124. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8125. for obj in d['objs']:
  8126. def obj_init(obj_inst, app_inst):
  8127. obj_inst.from_dict(obj)
  8128. App.log.debug("Recreating from opened project an %s object: %s" %
  8129. (obj['kind'].capitalize(), obj['options']['name']))
  8130. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8131. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8132. if cli is None:
  8133. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8134. obj['kind'].upper(),
  8135. obj['options']['name']
  8136. )
  8137. )
  8138. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8139. self.inform.emit('[success] %s: %s' %
  8140. (_("Project loaded from"), filename))
  8141. self.should_we_save = False
  8142. self.file_opened.emit("project", filename)
  8143. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8144. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8145. if cli is None:
  8146. self.set_ui_title(name=self.project_filename)
  8147. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8148. def propagate_defaults(self, silent=False):
  8149. """
  8150. This method is used to set default values in classes. It's
  8151. an alternative to project options but allows the use
  8152. of values invisible to the user.
  8153. :return: None
  8154. """
  8155. if silent is False:
  8156. self.log.debug("propagate_defaults()")
  8157. # Which objects to update the given parameters.
  8158. routes = {
  8159. "global_zdownrate": CNCjob,
  8160. "excellon_zeros": Excellon,
  8161. "excellon_format_upper_in": Excellon,
  8162. "excellon_format_lower_in": Excellon,
  8163. "excellon_format_upper_mm": Excellon,
  8164. "excellon_format_lower_mm": Excellon,
  8165. "excellon_units": Excellon,
  8166. "gerber_use_buffer_for_union": Gerber,
  8167. "geometry_multidepth": Geometry
  8168. }
  8169. for param in routes:
  8170. if param in routes[param].defaults:
  8171. try:
  8172. routes[param].defaults[param] = self.defaults[param]
  8173. if silent is False:
  8174. self.log.debug(" " + param + " OK")
  8175. except KeyError:
  8176. if silent is False:
  8177. self.log.debug(" ERROR: " + param + " not in defaults.")
  8178. else:
  8179. # Try extracting the name:
  8180. # classname_param here is param in the object
  8181. if param.find(routes[param].__name__.lower() + "_") == 0:
  8182. p = param[len(routes[param].__name__) + 1:]
  8183. if p in routes[param].defaults:
  8184. routes[param].defaults[p] = self.defaults[param]
  8185. if silent is False:
  8186. self.log.debug(" " + param + " OK!")
  8187. def restore_main_win_geom(self):
  8188. try:
  8189. self.ui.setGeometry(self.defaults["global_def_win_x"],
  8190. self.defaults["global_def_win_y"],
  8191. self.defaults["global_def_win_w"],
  8192. self.defaults["global_def_win_h"])
  8193. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  8194. except KeyError as e:
  8195. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  8196. def plot_all(self, zoom=True):
  8197. """
  8198. Re-generates all plots from all objects.
  8199. :return: None
  8200. """
  8201. self.log.debug("Plot_all()")
  8202. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8203. for obj in self.collection.get_list():
  8204. def worker_task(obj):
  8205. with self.proc_container.new("Plotting"):
  8206. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8207. if zoom:
  8208. self.object_plotted.emit(obj)
  8209. # Send to worker
  8210. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  8211. def register_folder(self, filename):
  8212. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8213. def register_save_folder(self, filename):
  8214. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8215. def set_progress_bar(self, percentage, text=""):
  8216. self.ui.progress_bar.setValue(int(percentage))
  8217. def setup_shell(self):
  8218. """
  8219. Creates shell functions. Runs once at startup.
  8220. :return: None
  8221. """
  8222. self.log.debug("setup_shell()")
  8223. def shelp(p=None):
  8224. if not p:
  8225. return _("Available commands:\n") + \
  8226. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  8227. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  8228. if p not in commands:
  8229. return "Unknown command: %s" % p
  8230. return commands[p]["help"]
  8231. # --- Migrated to new architecture ---
  8232. # def options(name):
  8233. # ops = self.collection.get_by_name(str(name)).options
  8234. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  8235. def h(*args):
  8236. """
  8237. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  8238. and standalone parameters into list.
  8239. """
  8240. kwa = {}
  8241. a = []
  8242. n = len(args)
  8243. name = None
  8244. for i in range(n):
  8245. match = re.search(r'^-([a-zA-Z].*)', args[i])
  8246. if match:
  8247. assert name is None
  8248. name = match.group(1)
  8249. continue
  8250. if name is None:
  8251. a.append(args[i])
  8252. else:
  8253. kwa[name] = args[i]
  8254. name = None
  8255. return a, kwa
  8256. @contextmanager
  8257. def wait_signal(signal, timeout=10000):
  8258. """
  8259. Block loop until signal emitted, timeout (ms) elapses
  8260. or unhandled exception happens in a thread.
  8261. :param timeout: time after which the loop is exited
  8262. :param signal: Signal to wait for.
  8263. """
  8264. loop = QtCore.QEventLoop()
  8265. # Normal termination
  8266. signal.connect(loop.quit)
  8267. # Termination by exception in thread
  8268. self.thread_exception.connect(loop.quit)
  8269. status = {'timed_out': False}
  8270. def report_quit():
  8271. status['timed_out'] = True
  8272. loop.quit()
  8273. yield
  8274. # Temporarily change how exceptions are managed.
  8275. oeh = sys.excepthook
  8276. ex = []
  8277. def except_hook(type_, value, traceback_):
  8278. ex.append(value)
  8279. oeh(type_, value, traceback_)
  8280. sys.excepthook = except_hook
  8281. # Terminate on timeout
  8282. if timeout is not None:
  8283. QtCore.QTimer.singleShot(timeout, report_quit)
  8284. # # ## Block ## ##
  8285. loop.exec_()
  8286. # Restore exception management
  8287. sys.excepthook = oeh
  8288. if ex:
  8289. self.raiseTclError(str(ex[0]))
  8290. if status['timed_out']:
  8291. raise Exception('Timed out!')
  8292. def make_docs():
  8293. output = ''
  8294. import collections
  8295. od = collections.OrderedDict(sorted(commands.items()))
  8296. for cmd_, val in od.items():
  8297. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  8298. t = val['help']
  8299. usage_i = t.find('>')
  8300. if usage_i < 0:
  8301. expl = t
  8302. output += expl + '\n\n'
  8303. continue
  8304. expl = t[:usage_i - 1]
  8305. output += expl + '\n\n'
  8306. end_usage_i = t[usage_i:].find('\n')
  8307. if end_usage_i < 0:
  8308. end_usage_i = len(t[usage_i:])
  8309. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  8310. else:
  8311. extras = t[usage_i+end_usage_i+1:]
  8312. parts = [s.strip() for s in extras.split('\n')]
  8313. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  8314. for p in parts:
  8315. output += ' ' + p + '\n\n'
  8316. return output
  8317. '''
  8318. Howto implement TCL shell commands:
  8319. All parameters passed to command should be possible to set as None and test it afterwards.
  8320. This is because we need to see error caused in tcl,
  8321. if None value as default parameter is not allowed TCL will return empty error.
  8322. Use:
  8323. def mycommand(name=None,...):
  8324. Test it like this:
  8325. if name is None:
  8326. self.raise_tcl_error('Argument name is missing.')
  8327. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  8328. otherwise we will miss it and processing will silently continue.
  8329. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  8330. which is catched in exec_command and displayed in TCL shell console with red background.
  8331. Error in console is displayed with TCL trace.
  8332. This behavior works only within main thread,
  8333. errors with promissed tasks can be catched and detected only with log.
  8334. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  8335. TCL shell.
  8336. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  8337. '''
  8338. commands = {
  8339. 'help': {
  8340. 'fcn': shelp,
  8341. 'help': _("Shows list of commands.")
  8342. },
  8343. }
  8344. # Import/overwrite tcl commands as objects of TclCommand descendants
  8345. # This modifies the variable 'commands'.
  8346. tclCommands.register_all_commands(self, commands)
  8347. # Add commands to the tcl interpreter
  8348. for cmd in commands:
  8349. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  8350. # Make the tcl puts function return instead of print to stdout
  8351. self.tcl.eval('''
  8352. rename puts original_puts
  8353. proc puts {args} {
  8354. if {[llength $args] == 1} {
  8355. return "[lindex $args 0]"
  8356. } else {
  8357. eval original_puts $args
  8358. }
  8359. }
  8360. ''')
  8361. def setup_recent_items(self):
  8362. # TODO: Move this to constructor
  8363. icons = {
  8364. "gerber": "share/flatcam_icon16.png",
  8365. "excellon": "share/drill16.png",
  8366. 'geometry': "share/geometry16.png",
  8367. "cncjob": "share/cnc16.png",
  8368. "project": "share/project16.png",
  8369. "svg": "share/geometry16.png",
  8370. "dxf": "share/dxf16.png",
  8371. "pdf": "share/pdf32.png",
  8372. "image": "share/image16.png"
  8373. }
  8374. openers = {
  8375. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8376. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8377. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8378. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8379. 'project': self.open_project,
  8380. 'svg': self.import_svg,
  8381. 'dxf': self.import_dxf,
  8382. 'image': self.import_image,
  8383. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8384. }
  8385. # Open recent file for files
  8386. try:
  8387. f = open(self.data_path + '/recent.json')
  8388. except IOError:
  8389. App.log.error("Failed to load recent item list.")
  8390. self.inform.emit('[ERROR_NOTCL] %s' %
  8391. _("Failed to load recent item list."))
  8392. return
  8393. try:
  8394. self.recent = json.load(f)
  8395. except json.scanner.JSONDecodeError:
  8396. App.log.error("Failed to parse recent item list.")
  8397. self.inform.emit('[ERROR_NOTCL] %s' %
  8398. _("Failed to parse recent item list."))
  8399. f.close()
  8400. return
  8401. f.close()
  8402. # Open recent file for projects
  8403. try:
  8404. fp = open(self.data_path + '/recent_projects.json')
  8405. except IOError:
  8406. App.log.error("Failed to load recent project item list.")
  8407. self.inform.emit('[ERROR_NOTCL] %s' %
  8408. _("Failed to load recent projects item list."))
  8409. return
  8410. try:
  8411. self.recent_projects = json.load(fp)
  8412. except json.scanner.JSONDecodeError:
  8413. App.log.error("Failed to parse recent project item list.")
  8414. self.inform.emit('[ERROR_NOTCL] %s' %
  8415. _("Failed to parse recent project item list."))
  8416. fp.close()
  8417. return
  8418. fp.close()
  8419. # Closure needed to create callbacks in a loop.
  8420. # Otherwise late binding occurs.
  8421. def make_callback(func, fname):
  8422. def opener():
  8423. func(fname)
  8424. return opener
  8425. def reset_recent_files():
  8426. # Reset menu
  8427. self.ui.recent.clear()
  8428. self.recent = []
  8429. try:
  8430. f = open(self.data_path + '/recent.json', 'w')
  8431. except IOError:
  8432. App.log.error("Failed to open recent items file for writing.")
  8433. return
  8434. json.dump(self.recent, f)
  8435. def reset_recent_projects():
  8436. # Reset menu
  8437. self.ui.recent_projects.clear()
  8438. self.recent_projects = []
  8439. try:
  8440. fp = open(self.data_path + '/recent_projects.json', 'w')
  8441. except IOError:
  8442. App.log.error("Failed to open recent projects items file for writing.")
  8443. return
  8444. json.dump(self.recent, fp)
  8445. # Reset menu
  8446. self.ui.recent.clear()
  8447. self.ui.recent_projects.clear()
  8448. # Create menu items for projects
  8449. for recent in self.recent_projects:
  8450. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8451. if recent['kind'] == 'project':
  8452. try:
  8453. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8454. # Attach callback
  8455. o = make_callback(openers[recent["kind"]], recent['filename'])
  8456. action.triggered.connect(o)
  8457. self.ui.recent_projects.addAction(action)
  8458. except KeyError:
  8459. App.log.error("Unsupported file type: %s" % recent["kind"])
  8460. # Last action in Recent Files menu is one that Clear the content
  8461. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8462. clear_action_proj.triggered.connect(reset_recent_projects)
  8463. self.ui.recent_projects.addSeparator()
  8464. self.ui.recent_projects.addAction(clear_action_proj)
  8465. # Create menu items for files
  8466. for recent in self.recent:
  8467. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8468. if recent['kind'] != 'project':
  8469. try:
  8470. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8471. # Attach callback
  8472. o = make_callback(openers[recent["kind"]], recent['filename'])
  8473. action.triggered.connect(o)
  8474. self.ui.recent.addAction(action)
  8475. except KeyError:
  8476. App.log.error("Unsupported file type: %s" % recent["kind"])
  8477. # Last action in Recent Files menu is one that Clear the content
  8478. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8479. clear_action.triggered.connect(reset_recent_files)
  8480. self.ui.recent.addSeparator()
  8481. self.ui.recent.addAction(clear_action)
  8482. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8483. # self.ui.menufilerecent.set_submenu(recent_menu)
  8484. # recent_menu.show_all()
  8485. # self.ui.recent.show()
  8486. self.log.debug("Recent items list has been populated.")
  8487. def setup_component_editor(self):
  8488. # label = QtWidgets.QLabel("Choose an item from Project")
  8489. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8490. sel_title = QtWidgets.QTextEdit(
  8491. _('<b>Shortcut Key List</b>'))
  8492. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8493. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8494. settings = QSettings("Open Source", "FlatCAM")
  8495. if settings.contains("notebook_font_size"):
  8496. fsize = settings.value('notebook_font_size', type=int)
  8497. else:
  8498. fsize = 12
  8499. tsize = fsize + int(fsize / 2)
  8500. # selected_text = (_('''
  8501. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  8502. #
  8503. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8504. # The normal flow when working in FlatCAM is the following:</span></p>
  8505. #
  8506. # <ol>
  8507. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  8508. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8509. # even dragging and dropping the files on the GUI.<br />
  8510. # <br />
  8511. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  8512. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8513. # &nbsp;</li>
  8514. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  8515. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8516. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8517. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8518. # <br />
  8519. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  8520. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8521. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8522. # it even if it was out of focus.<br />
  8523. # <br />
  8524. # You can change the parameters in this screen and the flow direction is like this:<br />
  8525. # <br />
  8526. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  8527. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8528. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8529. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8530. # </ol>
  8531. #
  8532. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8533. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8534. # <strong>F3</strong>.</span></p>
  8535. #
  8536. # ''').format(fsize=fsize, tsize=tsize))
  8537. selected_text = '''
  8538. <p><span style="font-size:{tsize}px"><strong>%s</strong></span></p>
  8539. <p><span style="font-size:{fsize}px"><strong>%s</strong>:<br />
  8540. %s:</span></p>
  8541. <ol>
  8542. <li><span style="font-size:{fsize}px">%s menu&#39;s, %s.<br />
  8543. <br />
  8544. %s &amp; %s.</span><br />
  8545. &nbsp;</li>
  8546. <li><span style="font-size:{fsize}px">%s <strong>%s</strong> (%s), <strong>%s</strong> %s it-s %s.<br />
  8547. <br />
  8548. %s <strong>%s</strong> %s <strong>%s</strong> %s.<br />
  8549. <br />
  8550. %s:<br />
  8551. <br />
  8552. <strong>%s</strong> -&gt; %s -&gt; %s -&gt;<strong> %s </strong> -&gt; %s -&gt; %s -&gt;<strong> %s
  8553. </strong>-&gt; %s <strong>%s)&nbsp;</strong>-&gt; %s</span></li>
  8554. </ol>
  8555. <p><span style="font-size:{fsize}px">%s <strong>%s -&gt; %s</strong>&nbsp;%s it&#39;s %s:
  8556. <strong>F3</strong>.</span></p>
  8557. ''' % (
  8558. _("Selected Tab - Choose an Item from Project Tab"), _("Details"),
  8559. _("The normal flow when working in FlatCAM is the following"),
  8560. _("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the"),
  8561. _("toolbars, key shortcuts or even dragging and dropping the files on the GUI"),
  8562. _("You can also load a FlatCAM project by double clicking on the project file, drag"),
  8563. _("drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app"),
  8564. _("Once an object is available in the Project Tab, by selecting it and then focusing on"),
  8565. _("SELECTED TAB"), _("more simpler is to double click the object name in the Project Tab"),
  8566. _("SELECTED TAB"), _("will be updated with the object properties according to"),
  8567. _("kind: Gerber, Excellon, Geometry or CNCJob object"),
  8568. _("If the selection of the object is done on the canvas by single click instead, and the"),
  8569. _("SELECTED TAB"),
  8570. _("is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, "
  8571. "double clicking on the object on the canvas will bring the"),
  8572. _("SELECTED TAB"), _("and populate it even if it was out of focus"),
  8573. _("You can change the parameters in this screen and the flow direction is like this"),
  8574. _("Gerber/Excellon Object"), _("Change Parameter"), _("Generate Geometry"), _("Geometry Object"),
  8575. _("Add tools (change param in Selected Tab)"), _("Generate CNCJob"), _("CNCJob Object"),
  8576. _("Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in"), _("SELECTED TAB"),
  8577. _("Save GCode"), _("A list of key shortcuts is available through an menu entry in"), _("Help"),
  8578. _("Shortcuts List"), _("or through"), _("own key shortcut"),
  8579. )
  8580. sel_title.setText(selected_text)
  8581. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8582. self.ui.selected_scroll_area.setWidget(sel_title)
  8583. def setup_obj_classes(self):
  8584. """
  8585. Sets up application specifics on the FlatCAMObj class.
  8586. :return: None
  8587. """
  8588. FlatCAMObj.app = self
  8589. ObjectCollection.app = self
  8590. Gerber.app = self
  8591. Excellon.app = self
  8592. Geometry.app = self
  8593. CNCjob.app = self
  8594. FCProcess.app = self
  8595. FCProcessContainer.app = self
  8596. def version_check(self):
  8597. """
  8598. Checks for the latest version of the program. Alerts the
  8599. user if theirs is outdated. This method is meant to be run
  8600. in a separate thread.
  8601. :return: None
  8602. """
  8603. self.log.debug("version_check()")
  8604. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8605. full_url = App.version_url + \
  8606. "?s=" + str(self.defaults['global_serial']) + \
  8607. "&v=" + str(self.version) + \
  8608. "&os=" + str(self.os) + \
  8609. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  8610. else:
  8611. # no_stats dict; just so it won't break things on website
  8612. no_ststs_dict = {}
  8613. no_ststs_dict["global_ststs"] = {}
  8614. full_url = App.version_url + \
  8615. "?s=" + str(self.defaults['global_serial']) + \
  8616. "&v=" + str(self.version) + \
  8617. "&os=" + str(self.os) + \
  8618. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8619. App.log.debug("Checking for updates @ %s" % full_url)
  8620. # ## Get the data
  8621. try:
  8622. f = urllib.request.urlopen(full_url)
  8623. except:
  8624. # App.log.warning("Failed checking for latest version. Could not connect.")
  8625. self.log.warning("Failed checking for latest version. Could not connect.")
  8626. self.inform.emit('[WARNING_NOTCL] %s' %
  8627. _("Failed checking for latest version. Could not connect."))
  8628. return
  8629. try:
  8630. data = json.load(f)
  8631. except Exception as e:
  8632. App.log.error("Could not parse information about latest version.")
  8633. self.inform.emit('[ERROR_NOTCL] %s' %
  8634. _("Could not parse information about latest version."))
  8635. App.log.debug("json.load(): %s" % str(e))
  8636. f.close()
  8637. return
  8638. f.close()
  8639. # ## Latest version?
  8640. if self.version >= data["version"]:
  8641. App.log.debug("FlatCAM is up to date!")
  8642. self.inform.emit('[success] %s' %
  8643. _("FlatCAM is up to date!"))
  8644. return
  8645. App.log.debug("Newer version available.")
  8646. self.message.emit(
  8647. _("Newer Version Available"),
  8648. _("There is a newer version of FlatCAM available for download:\n\n") +
  8649. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  8650. _("info")
  8651. )
  8652. def on_plotcanvas_setup(self, container=None):
  8653. """
  8654. This is doing the setup for the plot area (VisPy canvas)
  8655. :param container: widget where to install the canvas
  8656. :return: None
  8657. """
  8658. if container:
  8659. plot_container = container
  8660. else:
  8661. plot_container = self.ui.right_layout
  8662. self.plotcanvas = PlotCanvas(plot_container, self)
  8663. # So it can receive key presses
  8664. self.plotcanvas.native.setFocus()
  8665. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  8666. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  8667. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8668. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  8669. # Keys over plot enabled
  8670. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  8671. self.app_cursor = self.plotcanvas.new_cursor()
  8672. self.app_cursor.enabled = False
  8673. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8674. def on_zoom_fit(self, event):
  8675. """
  8676. Callback for zoom-out request. This can be either from the corresponding
  8677. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8678. with axes limits from the geometry bounds of all objects.
  8679. :param event: Ignored.
  8680. :return: None
  8681. """
  8682. self.plotcanvas.fit_view()
  8683. def on_zoom_in(self):
  8684. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8685. def on_zoom_out(self):
  8686. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8687. def disable_all_plots(self):
  8688. self.report_usage("disable_all_plots()")
  8689. self.disable_plots(self.collection.get_list())
  8690. self.inform.emit('[success] %s' %
  8691. _("All plots disabled."))
  8692. def disable_other_plots(self):
  8693. self.report_usage("disable_other_plots()")
  8694. self.disable_plots(self.collection.get_non_selected())
  8695. self.inform.emit('[success] %s' %
  8696. _("All non selected plots disabled."))
  8697. def enable_all_plots(self):
  8698. self.report_usage("enable_all_plots()")
  8699. self.enable_plots(self.collection.get_list())
  8700. self.inform.emit('[success] %s' %
  8701. _("All plots enabled."))
  8702. def on_enable_sel_plots(self):
  8703. log.debug("App.on_enable_sel_plot()")
  8704. object_list = self.collection.get_selected()
  8705. self.enable_plots(objects=object_list)
  8706. self.inform.emit('[success] %s' %
  8707. _("Selected plots enabled..."))
  8708. def on_disable_sel_plots(self):
  8709. log.debug("App.on_disable_sel_plot()")
  8710. # self.inform.emit(_("Disabling plots ..."))
  8711. object_list = self.collection.get_selected()
  8712. self.disable_plots(objects=object_list)
  8713. self.inform.emit('[success] %s' %
  8714. _("Selected plots disabled..."))
  8715. def enable_plots(self, objects):
  8716. """
  8717. Disables plots
  8718. :param objects: list of Objects to be enabled
  8719. :return:
  8720. """
  8721. log.debug("Enabling plots ...")
  8722. # self.inform.emit(_("Working ..."))
  8723. for obj in objects:
  8724. if obj.options['plot'] is False:
  8725. obj.options.set_change_callback(lambda x: None)
  8726. obj.options['plot'] = True
  8727. obj.options.set_change_callback(obj.on_options_change)
  8728. def worker_task(objects):
  8729. with self.proc_container.new(_("Enabling plots ...")):
  8730. for obj in objects:
  8731. # obj.options['plot'] = True
  8732. if isinstance(obj, FlatCAMCNCjob):
  8733. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8734. else:
  8735. obj.plot(visible=True)
  8736. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8737. # self.plots_updated.emit()
  8738. def disable_plots(self, objects):
  8739. """
  8740. Disables plots
  8741. :param objects: list of Objects to be disabled
  8742. :return:
  8743. """
  8744. # if no objects selected then do nothing
  8745. if not self.collection.get_selected():
  8746. return
  8747. log.debug("Disabling plots ...")
  8748. # self.inform.emit(_("Working ..."))
  8749. for obj in objects:
  8750. if obj.options['plot'] is True:
  8751. obj.options.set_change_callback(lambda x: None)
  8752. obj.options['plot'] = False
  8753. obj.options.set_change_callback(obj.on_options_change)
  8754. try:
  8755. self.delete_selection_shape()
  8756. except Exception as e:
  8757. log.debug("App.disable_plots() --> %s" % str(e))
  8758. # self.plots_updated.emit()
  8759. def worker_task(objects):
  8760. with self.proc_container.new(_("Disabling plots ...")):
  8761. for obj in objects:
  8762. # obj.options['plot'] = True
  8763. if isinstance(obj, FlatCAMCNCjob):
  8764. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8765. else:
  8766. obj.plot(visible=False)
  8767. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8768. def toggle_plots(self, objects):
  8769. """
  8770. Toggle plots visibility
  8771. :param objects: list of Objects for which to be toggled the visibility
  8772. :return:
  8773. """
  8774. # if no objects selected then do nothing
  8775. if not self.collection.get_selected():
  8776. return
  8777. log.debug("Toggling plots ...")
  8778. self.inform.emit(_("Working ..."))
  8779. for obj in objects:
  8780. if obj.options['plot'] is False:
  8781. obj.options['plot'] = True
  8782. else:
  8783. obj.options['plot'] = False
  8784. self.plots_updated.emit()
  8785. def clear_plots(self):
  8786. objects = self.collection.get_list()
  8787. for obj in objects:
  8788. obj.clear(obj == objects[-1])
  8789. # Clear pool to free memory
  8790. self.clear_pool()
  8791. def generate_cnc_job(self, objects):
  8792. self.report_usage("generate_cnc_job()")
  8793. # for obj in objects:
  8794. # obj.generatecncjob()
  8795. for obj in objects:
  8796. obj.on_generatecnc_button_click()
  8797. def save_project(self, filename, quit_action=False):
  8798. """
  8799. Saves the current project to the specified file.
  8800. :param filename: Name of the file in which to save.
  8801. :type filename: str
  8802. :param quit_action: if the project saving will be followed by an app quit; boolean
  8803. :return: None
  8804. """
  8805. self.log.debug("save_project()")
  8806. self.save_in_progress = True
  8807. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  8808. # Capture the latest changes
  8809. # Current object
  8810. try:
  8811. self.collection.get_active().read_form()
  8812. except:
  8813. self.log.debug("There was no active object")
  8814. pass
  8815. # Project options
  8816. self.options_read_form()
  8817. # Serialize the whole project
  8818. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8819. "options": self.options,
  8820. "version": self.version}
  8821. if self.defaults["global_save_compressed"] is True:
  8822. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8823. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8824. # # Write
  8825. f.write(g)
  8826. self.inform.emit('[success] %s: %s' %
  8827. (_("Project saved to"), filename))
  8828. else:
  8829. # Open file
  8830. try:
  8831. f = open(filename, 'w')
  8832. except IOError:
  8833. App.log.error("Failed to open file for saving: %s", filename)
  8834. return
  8835. # Write
  8836. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8837. f.close()
  8838. # verification of the saved project
  8839. # Open and parse
  8840. try:
  8841. saved_f = open(filename, 'r')
  8842. except IOError:
  8843. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8844. (_("Failed to verify project file"), filename, _("Retry to save it."))
  8845. )
  8846. return
  8847. try:
  8848. saved_d = json.load(saved_f, object_hook=dict2obj)
  8849. except:
  8850. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8851. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  8852. )
  8853. f.close()
  8854. return
  8855. saved_f.close()
  8856. if 'version' in saved_d:
  8857. self.inform.emit('[success] %s: %s' %
  8858. (_("Project saved to"), filename))
  8859. else:
  8860. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8861. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  8862. )
  8863. settings = QSettings("Open Source", "FlatCAM")
  8864. lock_state = self.ui.lock_action.isChecked()
  8865. settings.setValue('toolbar_lock', lock_state)
  8866. # This will write the setting to the platform specific storage.
  8867. del settings
  8868. # if quit:
  8869. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8870. # t.start()
  8871. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8872. def start_delayed_quit(self, delay, filename, should_quit=None):
  8873. """
  8874. :param delay: period of checking if project file size is more than zero; in seconds
  8875. :param filename: the name of the project file to be checked periodically for size more than zero
  8876. :param should_quit: if the task finished will be followed by an app quit; boolean
  8877. :return:
  8878. """
  8879. to_quit = should_quit
  8880. self.save_timer = QtCore.QTimer()
  8881. self.save_timer.setInterval(delay)
  8882. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8883. self.save_timer.start()
  8884. def check_project_file_size(self, filename, should_quit=None):
  8885. """
  8886. :param filename: the name of the project file to be checked periodically for size more than zero
  8887. :param should_quit: will quit the app if True; boolean
  8888. :return:
  8889. """
  8890. try:
  8891. if os.stat(filename).st_size > 0:
  8892. self.save_in_progress = False
  8893. self.save_timer.stop()
  8894. if should_quit:
  8895. self.app_quit.emit()
  8896. except Exception as e:
  8897. traceback.print_exc()
  8898. def on_options_app2project(self):
  8899. """
  8900. Callback for Options->Transfer Options->App=>Project. Copies options
  8901. from application defaults to project defaults.
  8902. :return: None
  8903. """
  8904. self.report_usage("on_options_app2project")
  8905. self.defaults_read_form()
  8906. self.options.update(self.defaults)
  8907. self.options_write_form()
  8908. def on_options_project2app(self):
  8909. """
  8910. Callback for Options->Transfer Options->Project=>App. Copies options
  8911. from project defaults to application defaults.
  8912. :return: None
  8913. """
  8914. self.report_usage("on_options_project2app")
  8915. self.options_read_form()
  8916. self.defaults.update(self.options)
  8917. self.defaults_write_form()
  8918. def on_options_project2object(self):
  8919. """
  8920. Callback for Options->Transfer Options->Project=>Object. Copies options
  8921. from project defaults to the currently selected object.
  8922. :return: None
  8923. """
  8924. self.report_usage("on_options_project2object")
  8925. self.options_read_form()
  8926. obj = self.collection.get_active()
  8927. if obj is None:
  8928. self.inform.emit('[WARNING_NOTCL] %s' %
  8929. _("No object selected."))
  8930. return
  8931. for option in self.options:
  8932. if option.find(obj.kind + "_") == 0:
  8933. oname = option[len(obj.kind) + 1:]
  8934. obj.options[oname] = self.options[option]
  8935. obj.to_form() # Update UI
  8936. def on_options_object2project(self):
  8937. """
  8938. Callback for Options->Transfer Options->Object=>Project. Copies options
  8939. from the currently selected object to project defaults.
  8940. :return: None
  8941. """
  8942. self.report_usage("on_options_object2project")
  8943. obj = self.collection.get_active()
  8944. if obj is None:
  8945. self.inform.emit('[WARNING_NOTCL] %s' %
  8946. _("No object selected."))
  8947. return
  8948. obj.read_form()
  8949. for option in obj.options:
  8950. if option in ['name']: # TODO: Handle this better...
  8951. continue
  8952. self.options[obj.kind + "_" + option] = obj.options[option]
  8953. self.options_write_form()
  8954. def on_options_object2app(self):
  8955. """
  8956. Callback for Options->Transfer Options->Object=>App. Copies options
  8957. from the currently selected object to application defaults.
  8958. :return: None
  8959. """
  8960. self.report_usage("on_options_object2app")
  8961. obj = self.collection.get_active()
  8962. if obj is None:
  8963. self.inform.emit('[WARNING_NOTCL] %s' %
  8964. _("No object selected."))
  8965. return
  8966. obj.read_form()
  8967. for option in obj.options:
  8968. if option in ['name']: # TODO: Handle this better...
  8969. continue
  8970. self.defaults[obj.kind + "_" + option] = obj.options[option]
  8971. self.defaults_write_form()
  8972. def on_options_app2object(self):
  8973. """
  8974. Callback for Options->Transfer Options->App=>Object. Copies options
  8975. from application defaults to the currently selected object.
  8976. :return: None
  8977. """
  8978. self.report_usage("on_options_app2object")
  8979. self.defaults_read_form()
  8980. obj = self.collection.get_active()
  8981. if obj is None:
  8982. self.inform.emit('[WARNING_NOTCL] %s' %
  8983. _("No object selected."))
  8984. return
  8985. for option in self.defaults:
  8986. if option.find(obj.kind + "_") == 0:
  8987. oname = option[len(obj.kind) + 1:]
  8988. obj.options[oname] = self.defaults[option]
  8989. obj.to_form() # Update UI
  8990. class ArgsThread(QtCore.QObject):
  8991. open_signal = pyqtSignal(list)
  8992. start = pyqtSignal()
  8993. if sys.platform == 'win32':
  8994. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8995. else:
  8996. address = ('/tmp/testipc', 'AF_UNIX')
  8997. def __init__(self):
  8998. super(ArgsThread, self).__init__()
  8999. self.start.connect(self.run)
  9000. def my_loop(self, address):
  9001. try:
  9002. listener = Listener(*address)
  9003. while True:
  9004. conn = listener.accept()
  9005. self.serve(conn)
  9006. except socket.error as e:
  9007. conn = Client(*address)
  9008. conn.send(sys.argv)
  9009. conn.send('close')
  9010. # close the current instance only if there are args
  9011. if len(sys.argv) > 1:
  9012. sys.exit()
  9013. def serve(self, conn):
  9014. while True:
  9015. msg = conn.recv()
  9016. if msg == 'close':
  9017. break
  9018. self.open_signal.emit(msg)
  9019. conn.close()
  9020. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9021. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9022. @pyqtSlot()
  9023. def run(self):
  9024. self.my_loop(self.address)
  9025. class GracefulException(Exception):
  9026. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  9027. def __init__(self):
  9028. super().__init__()
  9029. def __str__(self):
  9030. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  9031. # end of file